標籤:android style blog class code java
- android中,基本使用網路資源方式如下(同步)
try { URL url = new URL(myFeed); // Create a new HTTP URL connection URLConnection connection = url.openConnection(); HttpURLConnection httpConnection = (HttpURLConnection)connection; int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); processStream(in); } } catch (MalformedURLException e) { Log.d(TAG, "Malformed URL Exception.", e); } catch (IOException e) { Log.d(TAG, "IO Exception.", e); }
- 於此同時,android中解析XML主要有3種,分別為DOM解析器、SAX解析器和PULL解析器。
- DOM解析器,DomBuilder,通過DocumentBuilderFactory擷取。這兩個類都是javax包中定義的,不同於j2SE的是,android中重寫了後者,直接擷取了apache harmony的實現,不幸的是,harmony的項目在2011年時候已經被apache放棄了。
HttpURLConnection httpConnection = (HttpURLConnection) connection;int responseCode = httpConnection.getResponseCode();if (responseCode == httpConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); DocumentBuilderFactory dbf = DocumentBuilderFactory .newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); // 分析input Document dom = db.parse(in); Element docEle = dom.getDocumentElement();}
- SAX解析器。SAX是一個解析速度快並且佔用記憶體少的xml解析器,非常適合用於Android等行動裝置。 SAX解析XML檔案採用的是事件驅動,也就是說,它並不需要解析完整個文檔,在按內容順序解析文檔的過程中,SAX會判斷當前讀到的字元是否合法XML文法中的某部分,如果符合就會觸發事件。所謂事件,其實就是一些回調(callback)方法,這些方法(事件)定義在ContentHandler介面。
SAXParserFactory factory=SAXParserFactory.newInstance(); SAXParser parser=factory.newSAXParser(); MyHandel handel=new MyHandel (); //此處MyHandle繼承自DefaultHandelparser.parse(inputStream, handel);
- PULL解析器。以下來自android training,google比較推薦使用這個解析器
為什麼要學習PULL解析器呢?因為PULL解析是在XML文檔中尋找想要的標記,把需要的內容拉入記憶體,而不是把整個文檔都拉入記憶體,這種方式比較適合手機等記憶體有限的小型的行動裝置。 We recommend XmlPullParser
, which is an efficient and maintainable way to parse XML on Android. Historically Android has had two implementations of this interface:
KXmlParser
via XmlPullParserFactory.newPullParser()
.
ExpatPullParser
, via Xml.newPullParser()
.
factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser();