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).

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末荧止,一起剝皮案震驚了整個濱河市屹电,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌跃巡,老刑警劉巖危号,帶你破解...
    沈念sama閱讀 210,978評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異素邪,居然都是意外死亡外莲,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,954評論 2 384
  • 文/潘曉璐 我一進店門兔朦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來偷线,“玉大人,你說我怎么就攤上這事沽甥∩睿” “怎么了?”我有些...
    開封第一講書人閱讀 156,623評論 0 345
  • 文/不壞的土叔 我叫張陵摆舟,是天一觀的道長翔忽。 經(jīng)常有香客問我英融,道長,這世上最難降的妖魔是什么歇式? 我笑而不...
    開封第一講書人閱讀 56,324評論 1 282
  • 正文 為了忘掉前任驶悟,我火速辦了婚禮,結(jié)果婚禮上材失,老公的妹妹穿的比我還像新娘痕鳍。我一直安慰自己,他們只是感情好龙巨,可當我...
    茶點故事閱讀 65,390評論 5 384
  • 文/花漫 我一把揭開白布笼呆。 她就那樣靜靜地躺著,像睡著了一般旨别。 火紅的嫁衣襯著肌膚如雪诗赌。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,741評論 1 289
  • 那天秸弛,我揣著相機與錄音铭若,去河邊找鬼。 笑死递览,一個胖子當著我的面吹牛叼屠,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播绞铃,決...
    沈念sama閱讀 38,892評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼镜雨,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了儿捧?” 一聲冷哼從身側(cè)響起荚坞,我...
    開封第一講書人閱讀 37,655評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎菲盾,沒想到半個月后逆瑞,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體涩禀,經(jīng)...
    沈念sama閱讀 44,104評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡惫撰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年杆兵,在試婚紗的時候發(fā)現(xiàn)自己被綠了揪阿。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片疗我。...
    茶點故事閱讀 38,569評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖南捂,靈堂內(nèi)的尸體忽然破棺而出吴裤,到底是詐尸還是另有隱情,我是刑警寧澤溺健,帶...
    沈念sama閱讀 34,254評論 4 328
  • 正文 年R本政府宣布麦牺,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏剖膳。R本人自食惡果不足惜魏颓,卻給世界環(huán)境...
    茶點故事閱讀 39,834評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望吱晒。 院中可真熱鬧甸饱,春花似錦、人聲如沸仑濒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,725評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽墩瞳。三九已至驼壶,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間喉酌,已是汗流浹背热凹。 一陣腳步聲響...
    開封第一講書人閱讀 31,950評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留瞭吃,地道東北人碌嘀。 一個月前我還...
    沈念sama閱讀 46,260評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像歪架,于是被迫代替她去往敵國和親股冗。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,446評論 2 348

推薦閱讀更多精彩內(nèi)容