因為mobile device的電池容量有限,所以須考量widgets處理資料的效率,所以我們須:
1. Use an efficient parser to parse textual data. For XML data, use stream(event)-based parser (ex: XmlPullParser), not tree-based parser (ex: DOM). Otherwise the stream(event)-based parser has a much slimmer memory footprint.
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
GZIPInputStream is=getHTTPGZIPInputStream();
parser.setInput(is,null);
int eventType = parser.getEventType();
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
String tagname = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
//do something
break;
case XmlPullParser.START_TAG:
tagname=parser.getName();
//At the begin of tag with tagname, do something
break;
case XmlPullParser.END_TAG:
name = parser.getName();
//At the end of tag with tagname, do something
break;
}
eventType = parser.next();
}
is.close();
2. Use GZIP for text data whenever possible. The is the high tranfer rate between widgets and data sourcer. And the widget can parse the data efficiently.
URL feedUrl=new URL(""http://xml.weather.yahoo.com/forecastrss/TWXX0021_c.xml"");
InputStream is = null;
HttpURLConnection conn = (HttpURLConnection) feedUrl.openConnection();
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
int response = conn.getResponseCode();
if (response == 200){
is = conn.getInputStream();
if (conn.getHeaderField("Content-encoding") != null && conn.getHeaderField("Content-encoding").trim().toLowerCase().equals("gzip")){
is = new GZIPInputStream(is);
//Now we can use the GZIPInputStream is to do the data parsing.
}
refernce:
http://code.google.com/intl/zh-TW/events/io/sessions/CodingLifeBatteryLife.html
1 則留言:
我來是資策會,不曉得您是哪個公司,發展Android 手機(?) , 最近看到一篇文章
http://blog.xuite.net/star.sino/edithpan666/26078751
與您分享
張貼留言