Android System network connection status changes will send a broadcast, register a broadcast receiver, real-time dynamic detection network status, timely remind users, optimize the user experience.
This article only provides detection of WiFi status as a reference, other network connection methods please compare WiFi connection to make adjustments. First write a Wifistatebroadcast class inherit broadcastreceiver, rewrite the Onrecevie method, get the network connection state manager, get the corresponding network information through the manager, get the network state, judge the network status, make the corresponding business logic.
1 Public classWifistatebroadcastextendsBroadcastreceiver {2 @Override3 Public voidOnReceive (Context context, Intent Intent) {4 //Get manager5Connectivitymanager Connectivitymanager =(Connectivitymanager) Context.getsystemservice (context.connectivity_service);6 //Get WiFi status7Networkinfo.state State =Connectivitymanager.getnetworkinfo (Connectivitymanager.type_wifi). GetState ();8 if(state! =NetworkInfo.State.CONNECTED) {9Toast.maketext (Context, "WiFi is disconnected", Toast.length_short). Show ();Ten}Else if(state = =NetworkInfo.State.CONNECTED) { OneToast.maketext (Context, "WiFi is connected", Toast.length_short). Show (); A } - } -}
Then register the broadcast statically in the manifest file
1 <receiver android:name= ". Broadcast. Wifistatebroadcast ">2 <intent-filter>3 <action android:name=" Android.net.conn.CONNECTIVITY_CHANGE "/>4 </intent-filter>5 </ Receiver>
Don't forget to add permissions
1 <uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/>2 <uses-permission Android:name= "Android.permission.INTERNET"/>3 <uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/>
In this way, when the cellular network changes, it can be timely to deal with, to prevent some overly dependent programs do not work properly.
Android gets network status via broadcast