public class Networkstatereceiver extends Broadcastreceiver {@Override public void onreceive (context context, Inten T intent) {SYSTEM.OUT.PRINTLN ("network status Changed"); The detection API is not less than 23 because the getnetworkinfo (int networktype) method is deprecated if API23 (Android.os.Build.VERSION.SDK_INT < Android.os . Build.version_codes. LOLLIPOP) {//Get Connectivitymanager object Connectivitymanager connmgr = (connectivitymanager) context.ge Tsystemservice (Context.connectivity_service); Gets the Networkinfo object corresponding to the Connectivitymanager object//Get WiFi connection information networkinfo Wifinetworkinfo = connmgr.getnet Workinfo (Connectivitymanager.type_wifi); Get information about a mobile data connection networkinfo Datanetworkinfo = Connmgr.getnetworkinfo (connectivitymanager.type_mobile); if (wifinetworkinfo.isconnected () && datanetworkinfo.isconnected ()) {Toast.maketext (context, "WI Fi connected, mobile data Connected ", Toast.length_short). Show (); } else if (wifinetworkinfo. isconnected () &&!datanetworkinfo.isconnected ()) {Toast.maketext (context, "WiFi is connected, mobile data is disconnected", Toas T.length_short). Show (); } else if (!wifinetworkinfo.isconnected () && datanetworkinfo.isconnected ()) {Toast.maketext (Contex T, "WiFi is disconnected, mobile data is connected", Toast.length_short). Show (); } else {Toast.maketext (context, "WiFi disconnected, mobile data Disconnected", Toast.length_short). Show (); }//api greater than 23 use the following method for network monitoring}else {System.out.println ("API level greater than 23"); Get Connectivitymanager object Connectivitymanager connmgr = (Connectivitymanager) context.getsystemservice (context. Connectivity_service); Get information on all network connections network[] networks = Connmgr.getallnetworks (); For storing network connection information StringBuilder SB = new StringBuilder (); The network information is taken out one by one for (int i=0; i < networks.length; i++) {//Get the networks of the Connectivitymanager objects Info Object Networkinfo networkinfo = Connmgr.getnetworkinfo (Networks[i]); Sb.append (Networkinfo.gettypename () + "Connect is" + networkinfo.isconnected ()); } toast.maketext (Context, sb.tostring (), Toast.length_short). Show (); } }}
Registering the listener in the Ingress class
<uses-sdk> <uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/> </ Uses-sdk>
Android Network Monitoring