標籤:
原文地址:http://android.xsoftlab.net/training/basics/network-ops/managing.html
這節課將會學習如何對網路資源的使用方式擁有更細粒度的控制力。如果應用程式經常執行大量的網路操作,那麼程式應當提供一項設定,以便使用者可以控制應用的資料習性,比如多久同步一次資料,是否只在WIFI情況下上傳下載資料,是否使用移動資料流量等等。隨著這些設定能力的提供,使用者可以設定應用在接近網路流量限制的情況下禁止應用再次訪問網路,因為使用者可以直接控制應用程式可以使用多少資料流量。
檢測裝置的網路連接狀況
一台裝置擁有多種類型的網路連接。這節課所關注的是使用WI-FI或者移動資料網路連接。有關全面的網路連接類型,請參見ConnectivityManager.
WIFI通常情況下很快,而移動資料通常按量收費,還很昂貴。APP的通常使用原則是在WIFI網路可用的情況下才去擷取大量的資料。
在執行網路操作之前,最好是檢查一下網路的串連狀態。執行網路狀態檢查,通常會使用到下面的類:
- ConnectivityManager : 可以擷取當前網路的串連狀況,還可以在網路連接狀況發生變化時通知應用程式。
- NetworkInfo : 描述了指定類型的網路介面狀態。
下面的代碼測試了WIFI及移動資料的串連狀態。它會檢查這些網路介面是否可用及是否已串連:
private static final String DEBUG_TAG = "NetworkStatusExample";... ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); boolean isWifiConn = networkInfo.isConnected();networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);boolean isMobileConn = networkInfo.isConnected();Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);
需要注意的是,不應當關注網路是否可用,而應該在每次執行網路操作之前檢查isConnected(),因為isConnected()會處理這些狀態:移動網路訊號不好、飛航模式或者受限的後台資料。
有一種更簡明的方式可以用來檢查網路介面是否可用:getActiveNetworkInfo()方法會返回一個NetworkInfo的執行個體,這個對象代表了所能搜尋到的第一個已串連的網路介面,如果沒有搜尋到任何網路連接則會返回null,null代表了互連網絡串連不餓用。
public boolean isOnline() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected());}
你可以使用NetworkInfo.DetailedState查詢更細粒度的網路狀態,不過很少會被用到。
管理網路的使用
可以通過實現一個參數設定的Activity來讓使用者控制網路資源的使用。
- 你可能只允許使用者在WIFI網路狀態下才可以上傳視頻資源。
- 你可能要允許使用者佈建在指定的條件下才去同步資料,比如:網路可用狀態下,或者隔多長時間等等。
為了使APP可以支援網路的訪問及網路使用的管理,那麼資訊清單檔中必須包含以下許可權以及意圖過濾器:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.networkusage" ...> <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application ...> ... <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> </application></manifest>
實現一個參數配置Activity
正如你在上面所看到的,SettingsActivity的意圖過濾器含有一個ACTION_MANAGE_NETWORK_USAGE的行為,SettingsActivity是PreferenceActivity的子類,它的展示效果如下:
下面是SettingsActivity的代碼,注意它實現了OnSharedPreferenceChangeListener介面。每當使用者更改了參數,系統會調用onSharedPreferenceChanged()方法,該方法內將refreshDisplay設定為true,這是因為當使用者返回到主介面是需要重新整理介面。
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Loads the XML preferences file addPreferencesFromResource(R.xml.preferences); } @Override protected void onResume() { super.onResume(); // Registers a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); // Unregisters the listener set in onResume(). // 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); } // When the user changes the preferences selection, // onSharedPreferenceChanged() restarts the main activity as a new // task. Sets the refreshDisplay flag to "true" to indicate that // the main activity should update its display. // The main activity queries the PreferenceManager to get the latest settings. @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // 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; }}
響應參數的變更
當使用者更改了參數時,這個行為會使APP的習性也跟著發生了變化。在下面的程式碼片段中,APP會在onStart()方法中檢查參數配置,如果在裝置的當前串連狀態與設定之間有相匹配的,那麼APP將會下載資訊,並重新整理介面。
public class NetworkActivity extends Activity { public static final String WIFI = "Wi-Fi"; public static final String ANY = "Any"; private static final String URL = "http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest"; // Whether there is a Wi-Fi connection. private static boolean wifiConnected = false; // Whether there is a mobile connection. private static boolean mobileConnected = false; // Whether the display should be refreshed. public static boolean refreshDisplay = true; // The user‘s current network preference setting. public static String sPref = null; // The BroadcastReceiver that tracks network connectivity changes. private NetworkReceiver receiver = new NetworkReceiver(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Registers BroadcastReceiver to track network connection changes. IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); receiver = new NetworkReceiver(); this.registerReceiver(receiver, filter); } @Override public void onDestroy() { super.onDestroy(); // Unregisters BroadcastReceiver when app is destroyed. if (receiver != null) { this.unregisterReceiver(receiver); } } // Refreshes the display if the network connection and the // pref settings allow it. @Override public void onStart () { super.onStart(); // Gets the user‘s network preference settings SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // Retrieves a string value for the preferences. The second parameter // is the default value to use if a preference value is not found. sPref = sharedPrefs.getString("listPref", "Wi-Fi"); updateConnectedFlags(); if(refreshDisplay){ loadPage(); } } // Checks the network connection and sets the wifiConnected and mobileConnected // variables accordingly. public void updateConnectedFlags() { 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; } } // Uses AsyncTask subclass to download the XML feed from stackoverflow.com. public void loadPage() { if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected)) || ((sPref.equals(WIFI)) && (wifiConnected))) { // AsyncTask subclass new DownloadXmlTask().execute(URL); } else { showErrorPage(); } }...}
監聽串連變化
最後一個問題就是BroadcastReceiver的子類NetworkReceiver。當裝置的網路連接發生變化時,NetworkReceiver會攔截CONNECTIVITY_ACTION的行為,這個行為用於檢查當前是哪種網路連接狀態,並會相應的將wifiConnected和mobileConnected設定為true或者false。那麼在NetworkActivity.refreshDisplay設定為true時,那麼APP會只下載最近一次的資源。
設定的廣播監聽器需要在系統不需要的情況下解除註冊。樣本應用中在onCreate()方法中將NetworkReceiver註冊到系統,在onDestroy()方法中將其登出。這比在資訊清單檔中註冊更為輕量。當在資訊清單檔中聲明了廣播接收器,系統會在任何時候調用該接收器,甚至是很久都沒有啟動過。在Activity中註冊與登出廣播接收器,可以確保使用者在離開APP後系統不會再調用廣播接收器。如果在資訊清單檔中註冊了廣播接收器,那麼你必須清楚在什麼地方需要它,你可以適當的使用setComponentEnabledSetting()方法來開啟或者關閉它。
以下是 NetworkReceiver 的實現內容:
public class NetworkReceiver extends BroadcastReceiver { @Overridepublic void onReceive(Context context, Intent intent) { ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); // 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(); }}
Android官方開發文檔Training系列課程中文版:網路操作之網路管理