Performing Network Operations

Smaple - NetworkUsage

Android Training Link

  • Downloads an XML feed from StackOverflow.com for the most recent posts tagged "android".
  • Parses the XML feed, combines feed elements with HTML markup, and displays the resulting HTML in the UI.
  • Lets users control their network data usage through a settings UI. Users can choose to fetch the feed when any network connection is available, or only when a Wi-Fi connection is available.
  • Detects when there is a change in the device's connection status and responds accordingly. For example, if the device loses its network connection, the app will not attempt to download the feed.

1. Manifest

  • Permissions
    1. INTERNET
    2. ACCESS_NETWORK_STATE
  • Activity
<activity android:label="SettingsActivity" android:name=".SettingsActivity">
     <intent-filter>
        <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" />
        <category android:name="android.intent.category.DEFAULT" />
     </intent-filter>
</activity>

2. SettingsActivity extends PreferenceActivity

implements OnSharedPreferenceChangeListener

  • onCreate()
// Loads the XML preferences file.
addPreferencesFromResource(R.xml.preferences);
  • onResume()
// Registers a callback to be invoked whenever a user changes a preference.
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
  • onPause()
// It's best practice to unregister listeners when your app isn't using them to cut down on
// unnecessary system overhead. You do this in onPause().
getPreferenceScreen()
.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
  • overrides onSharedPreferenceChanged()
// Sets refreshDisplay to true so that when the user returns to the main
// activity, the display refreshes to reflect the new settings.
NetworkActivity.refreshDisplay = true;

3. preferences.xml

  • ListPreference
android:key="listPref"
android:defaultValue="Wi-Fi"
android:entries="@array/listArray"
android:entryValues="@array/listValues"
<resources>
    <string-array name="listArray">
        <item>Only when on Wi-Fi</item>
        <item>On any network</item>
    </string-array>
    <string-array name="listValues">
        <item>Wi-Fi</item>
        <item>Any</item>
    </string-array>
</resources>
  • CheckBoxPreference

4. NetworkActivity

  • onCreate()
// Register BroadcastReceiver to track connection changes.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkReceiver();
this.registerReceiver(receiver, filter);
  • onStart()
    Refreshes the display if the network connection and the pref settings allow it.
  • updateConnectedFlags()
  • loadPage()
if (refreshDisplay) {
        loadPage();
}
  • onDestroy()

  • unregisterReceiver

  • updateConnectedFlags()
    Checks the network connection and sets the wifiConnected and mobileConnected variables accordingly.

ConnectivityManager connMgr =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
    wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
    mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;}
 else {
    wifiConnected = false;
    mobileConnected = false;}
  • loadPage()

// Uses AsyncTask subclass to download the XML feed from stackoverflow.com.
// This avoids UI lock up. To prevent network operations from
// causing a delay that results in a poor user experience, always perform
// network operations on a separate thread from the UI.
Uses a AsyncTask subclass

new DownloadXmlTask().execute(URL);
  • DownloadXmlTask extends AsyncTask<String, Void, String>
  • doInBackground(String... urls)
return loadXmlFromNetwork(urls[0]);
  • onPostExecute(String result)
myWebView.loadData(result, "text/html", null);
  • loadXmlFromNetwork(String urlString)
    // Uploads XML from stackoverflow.com, parses it, and combines it with
    // HTML markup. Returns HTML string.
StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();

Checks whether the user set the preference to include summary text.

SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean pref = sharedPrefs.getBoolean("summaryPref", false);

Downloads & Parses

stream = downloadUrl(urlString);
entries = stackOverflowXmlParser.parse(stream);

StackOverflowXmlParser returns a List (called "entries") of Entry objects.
Each Entry object represents a single post in the XML feed.
This section processes the entries list to combine each entry with HTML markup.
Each entry is displayed in the UI as a link that optionally includes// a text summary.

for (Entry entry : entries) {
    htmlString.append("<p><a href='");
    htmlString.append(entry.link);
    htmlString.append("'>" + entry.title + "</a></p>");
    // If the user set the preference to include summary text,
    // adds it to the display.
    if (pref) {
        htmlString.append(entry.summary);
    }
}
  • downloadUrl(String urlString)
    Given a string representation of a URL, sets up a connection and gets an input stream.

  • NetworkReceiver extends BroadcastReceiver

overrides onReceive()

// Checks the user prefs and the network connection. Based on the result, decides
// whether
// to refresh the display or keep the current display.
// If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
if (WIFI.equals(sPref) && networkInfo != null        
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {    
// If device has its Wi-Fi connection, sets refreshDisplay    
// to true. This causes the display to be refreshed when the user    
// returns to the app.    
refreshDisplay = true;    
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();    
// If the setting is ANY network and there is a network connection    
// (which by process of elimination would be mobile), sets refreshDisplay to true.
} else if (ANY.equals(sPref) && networkInfo != null) {    
refreshDisplay = true;    
// Otherwise, the app can't download content--either because there is no network    
// connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there    
// is no Wi-Fi connection.    
// Sets refreshDisplay to false.
} else {    
refreshDisplay = false;    
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();}

5. StackOverflowXmlParser

  • Instantiate the Parser.
public List<Entry> parse(InputStream in) throws XmlPullParserException, IOException {
    try {
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        parser.setInput(in, null);
        parser.nextTag();
        return readFeed(parser);
    } finally {
        in.close();
    }
}
  • readFeed()
  • Start with tag "feed"
  • Look for tag "entry"
  • Add "readEntry(parser)" to list<Entry>
private List<Entry> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
    List<Entry> entries = new ArrayList<Entry>();
    parser.require(XmlPullParser.START_TAG, ns, "feed");
    while (parser.next() != XmlPullParser.END_TAG) {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            continue;
        }
        String name = parser.getName();
        // Starts by looking for the entry tag
        if (name.equals("entry")) {
            entries.add(readEntry(parser));
        } else {
            skip(parser);
        }
    }
    return entries;
}
  • readEntry()
    Parses the contents of an entry.
    If it encounters a title, summary, or link tag, hands them off to their respective "read" methods for processing. Otherwise, skips the tag.
 private Entry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
        parser.require(XmlPullParser.START_TAG, ns, "entry");
        String title = null;
        String summary = null;
        String link = null;
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String name = parser.getName();
            if (name.equals("title")) {
                title = readTitle(parser);
            } else if (name.equals("summary")) {
                summary = readSummary(parser);
            } else if (name.equals("link")) {
                link = readLink(parser);
            } else {
                skip(parser);
            }
        }
        return new Entry(title, summary, link);
    }
  • read method & skip()
private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
            case XmlPullParser.END_TAG:
                    depth--;
                    break;
            case XmlPullParser.START_TAG:
                    depth++;
                    break;
            }
        }
    }

if the next tag after a START_TAG isn't a matching END_TAG, it keeps going until it finds the matching END_TAG (as indicated by the value of "depth" being 0).

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容