Original address: http://android.xsoftlab.net/training/basics/network-ops/managing.html
This lesson will learn how to have finer-grained control over the use of network resources. If your application often performs a large number of network operations, the program should provide a setting so that the user can control the data habits of the app, such as how often to synchronize data, whether to upload downloaded data only in the case of WiFi, whether to use mobile data traffic, and so on. With these provisioning capabilities, users can set the app to prohibit the app from accessing the network again, near network traffic limits, because users can directly control how much data traffic the application can use.
Detecting the network connection status of the device
A single device has multiple types of network connectivity. This lesson is focused on using Wi-Fi or mobile data networking connections. For a comprehensive network connection type, see Connectivitymanager.
WiFi is usually fast, and mobile data is usually metered and expensive. The usual use of the app is to get a lot of data when the WiFi network is available.
Before performing a network operation, it is best to check the network connection status. Perform a network status check, typically using the following classes:
- Connectivitymanager: You can get the current network connection status, and you can also notify the application when the network connection condition changes.
- Networkinfo: Describes the network interface state of the specified type.
The following code tests the connection status of WiFi and mobile data. It checks to see if the network interfaces are available and connected:
privatestaticfinal"NetworkStatusExample";... ConnectivityManager connMgr = (ConnectivityManager) boolean isWifiConn = networkInfo.isConnected();networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);boolean"Wifi connected: ""Mobile connected: " + isMobileConn);
It should be noted that you should not be concerned about the availability of the network, but should check for isconnected () before each network operation, because IsConnected () will handle these states: poor mobile network signal, flight mode, or limited background data.
There is a more concise way to check if a network interface is available: the Getactivenetworkinfo () method returns an instance of Networkinfo that represents the first connected network interface that can be searched. If no network connection is found, the null,null will be returned, which means the Internet connection is not hungry.
publicbooleanisOnline() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); returnnull && networkInfo.isConnected());}
You can use Networkinfo.detailedstate to query for finer-grained network state, but it is rarely used.
Managing the use of the network
You can enable users to control the use of network resources by implementing a parameter setting activity.
- You may only allow users to upload video resources while in the WiFi network state.
- You may want to allow the user to set the data to be synchronized under the specified conditions, such as when the network is available, or how long it takes to wait.
In order for the app to support network access and management of network usage, the following permissions and intent filters must be included in the manifest file:
The manifest file should contain the following permissions:
- Android.permission.INTERNET allows applications to access the network jack (socket).
- Android.permission.ACCESS_NETWORK_STATE allows applications to access network information.
You can indicate that the current activity provides the ability to control the data usage policy by declaring Action_manage_network_usage's intent filter. This intent filter should be declared when the app contains activity that allows users to manage network data usage policies. In the example program here, this behavior is handled by Settingsactivity, which allows the user to decide when to start the download.
<?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>
Implementing a parameter configuration activity
As you can see above, Settingsactivity's intent filter contains a action_manage_network_usage behavior, Settingsactivity is a subclass of Preferenceactivity, It shows the following effects:
Here is the code for Settingsactivity, note that it implements the Onsharedpreferencechangelistener interface. Whenever the user changes the parameters, the system calls the Onsharedpreferencechanged () method, which sets the refreshdisplay to true, because the interface needs to be refreshed when the user returns to the main interface.
public class Settingsactivity extends Preferenceactivity implements Onsharedpreferencechangelistener {@Override Pro tected 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 (). registerons Haredpreferencechangelistener (this); } @Override protected void OnPause () {super.onpause (); Unregisters the Listener set in Onresume (). It's best practice to unregister listeners when your app is ' t using them to cut down on//unnecessary system O Verhead. 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, 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 R Efreshdisplay to true so that's when the user returns to the main/activity, the display refreshes to reflect the N EW settings. Networkactivity.refreshdisplay = true; }}
Changes to response parameters
When the user changes the parameters, this behavior changes the app's habits as well. In the following code snippet, the app checks the parameter configuration in the OnStart () method, and if there is a match between the device's current connection state and the setting, the app will download the information and refresh the interface.
Public class networkactivity extends Activity { Public Static FinalString WIFI ="Wi-Fi"; Public Static FinalString any ="any";Private Static FinalString URL ="Http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest";//Whether There is a Wi-Fi connection. Private Static Booleanwificonnected =false;//Whether There is a mobile connection. Private Static Booleanmobileconnected =false;//Whether The display should be refreshed. Public Static BooleanRefreshdisplay =true;//The user ' s current network preference setting. Public StaticString Spref =NULL;//The broadcastreceiver that tracks network connectivity changes. PrivateNetworkreceiver receiver =NewNetworkreceiver ();@Override Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//registers Broadcastreceiver to track network connection changes.Intentfilter filter =NewIntentfilter (connectivitymanager.connectivity_action); Receiver =NewNetworkreceiver (); 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 settingsSharedpreferences sharedprefs = preferencemanager.getdefaultsharedpreferences ( This);//Retrieves a string value for the preferences. The second parameter //is the default value, and 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_serv ICE); 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 NewDownloadxmltask (). Execute (URL); }Else{showerrorpage (); } }...}
Monitor connection changes
The last problem is the subclass of Broadcastreceiver Networkreceiver. When a device's network connection changes, Networkreceiver intercepts the behavior of connectivity_action, which is used to check which network connection status is currently in place. The wificonnected and mobileconnected are set to TRUE or false accordingly. Then when Networkactivity.refreshdisplay is set to True, the app downloads only the last resource.
The broadcast listener you set up needs to be unregistered if the system is not needed. The sample app registers networkreceiver with the system in the OnCreate () method and unregisters it in the OnDestroy () method. This is more lightweight than registering in the manifest file. When a broadcast sink is declared in the manifest file, the system will call the sink at any time, even if it has not been started for a long time. Registering and unregistering a broadcast receiver in activity ensures that the system no longer calls the broadcast receiver after leaving the app. If you register a broadcast receiver in the manifest file, you must know where it is needed and you can use the Setcomponentenabledsetting () method to turn it on or off.
Here's what Networkreceiver is for:
Public class networkreceiver extends broadcastreceiver { @Override Public 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 being 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 is 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 Official Development Document Training Series Chinese version: Network management of network operation