Android phone changes to the state of the system, such as: the receipt of the letter, telephone reception, battery power is too low, the network status changes will send a broadcast. With the broadcast mechanism, we only need to create a broadcast recipient to deal with this broadcast, we can achieve in different states to make different operations,
This article mainly records the network status change monitoring. First define a class to inherit networkchangereceiver, and rewrite OnReceive () on the line. The corresponding broadcast is then processed in the OnReceive () method.
Public class Networkreceiver extends Broadcastreceiver {
Public voidOnReceive (Context context, Intent Intent) {State wifistate=NULL; State Mobilestate=NULL; Connectivitymanager cm=(Connectivitymanager) context. Getsystemservice (Context.connectivity_service); Wifistate=Cm.getnetworkinfo (Connectivitymanager.type_wifi). GetState (); Mobilestate=Cm.getnetworkinfo (connectivitymanager.type_mobile). GetState (); if(Mobilestate! =NULL&& state.connected = =mobilestate) { //Mobile network Connection successful if(Cm.getactivenetworkinfo (). Getextrainfo (). toLowerCase (). Equals ("Cmnet")) { //Cmnet Links}Else{ //cmwap link, add China Mobile Agent
Httphost proxy = new Httphost ("10.0.0.172", 80);
conn = (httpurlconnection) url.openconnection (proxy);
} elseif (state.connected! = wifistate&& state.connected ! = mobilestate) {// phone does not have any network elseifnull && state.connected = = wifistate) {/// Wireless network connection successful }} }
Then, we need to register this broadcast in the app, there are two ways to register the broadcast, ① to register in Androidmanifest.xml
<receiverAndroid:name= "Com.test.NetworkBroadcast"Android:label= "Networkconnection" > <Intent-filter> <ActionAndroid:name= "Android.net.conn.CONNECTIVITY_CHANGE" /> </Intent-filter></receiver>
② is registered in the Java code, registered in the activity's OnCreate () method, unloaded in the Ondestory () method
Private Broadcastreceiver networkbroadcast=Newnew// Set Priority Filter.setpriority (integer.max_value); this. Registerreceiver (networkbroadcast, filter);
Unloading:
if NULL ) { this. Unregisterreceiver (networkbroadcast); Networkbroadcast=null;}
③ Adding permissions
<android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
If the program is hidden in the background, it is recommended to open a service, the Broadcastreceiver registered in the service. such as phone interception, IP dialing, detection of SD card status, boot status and so on.
Internet link status for Android