你可以为你的设置Activity声明intent filter for the ACTION_MANAGE_NETWORK_USAGE action (introduced in Android 4.0),这样你的这个activity就可以提供数据控制的选项了。在章节概览提供的Sample中,这个action is handled by the class SettingsActivity, 它提供了偏好设置UI来让用户决定何时进行下载。
publicclassSettingsActivityextendsPreferenceActivityimplementsOnSharedPreferenceChangeListener{@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);// Loads the XML preferences fileaddPreferencesFromResource(R.xml.preferences);}@OverrideprotectedvoidonResume(){super.onResume();// Registers a listener whenever a key changes getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);}@OverrideprotectedvoidonPause(){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 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.@OverridepublicvoidonSharedPreferenceChanged(SharedPreferencessharedPreferences,Stringkey){// 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;}}
Respond to Preference Changes(对偏好改变进行响应)
当用户在设置界面改变了偏好,它通常都会对app的行为产生影响。
在下面的代码示例中,app会在onStart(). 方法里面检查偏好设置。如果设置的类型与当前设备的网络连接类型相一致,那么程序就会下载数据并刷新显示。(for example, if the setting is “Wi-Fi” and the device has a Wi-Fi connection)。(这是一个很好的代码示例,如何选择合适的网络类型进行下载操作)
publicclassNetworkActivityextendsActivity{publicstaticfinalStringWIFI="Wi-Fi";publicstaticfinalStringANY="Any";privatestaticfinalStringURL="http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";// Whether there is a Wi-Fi connection.privatestaticbooleanwifiConnected=false;// Whether there is a mobile connection.privatestaticbooleanmobileConnected=false;// Whether the display should be refreshed.publicstaticbooleanrefreshDisplay=true;// The user's current network preference setting.publicstaticStringsPref=null;// The BroadcastReceiver that tracks network connectivity changes.privateNetworkReceiverreceiver=newNetworkReceiver();@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);// Registers BroadcastReceiver to track network connection changes.IntentFilterfilter=newIntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);receiver=newNetworkReceiver();this.registerReceiver(receiver,filter);}@OverridepublicvoidonDestroy(){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.@OverridepublicvoidonStart(){super.onStart();// Gets the user's network preference settingsSharedPreferencessharedPrefs=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. publicvoidupdateConnectedFlags(){ConnectivityManagerconnMgr=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfoactiveInfo=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.publicvoidloadPage(){if(((sPref.equals(ANY))&&(wifiConnected||mobileConnected))||((sPref.equals(WIFI))&&(wifiConnected))){// AsyncTask subclassnewDownloadXmlTask().execute(URL);}else{showErrorPage();}}...}
publicclassNetworkReceiverextendsBroadcastReceiver{@OverridepublicvoidonReceive(Contextcontext,Intentintent){ConnectivityManagerconn=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfonetworkInfo=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.}elseif(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();}}