In this example, a simple case of network state change of listening system is realized by broadcasting. 1. Demonstration of case effect
When the phone is connected to the network, the system prompts
When the phone is disconnected, the system prompts "the current network is not available for 1". 2, case implementation in the main activity to dynamically register the broadcast, and then write an internal class to receive the system broadcast, the following is the core code of the relevant files: Mainactivity.java:
Public class Mainactivity extends Appcompatactivity {
private Intentfilter Intentfilter;
private Networkchangereceiver networkchangereceiver;
@Override
protected void OnCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
// Dynamic registration of broadcasts
intentfilter = new Intentfilter ();
intentfilter.addaction("Android.net.conn.CONNECTIVITY_CHANGE");
networkchangereceiver = new Networkchangereceiver ();
registerreceiver (Networkchangereceiver, intentfilter);
}
/**
* activity is closed after execution
*/
@Override
protected void OnDestroy () {
Super.ondestroy ();
Unregisterreceiver (networkchangereceiver);
}
class Networkchangereceiver extends broadcastreceiver {// define an inner class to receive the broadcast
@Override
Public void OnReceive (context context, Intent Intent) {
//Toast.maketext (context, " network status changed! ",
//Toast.length_short). Show ();
connectivitymanager connectivitymanager = (connectivitymanager) getsystemservice(C Ontext. Connectivity_service);
networkinfo networkinfo = Connectivitymanager.getactivenetworkinfo ();
if (networkinfo! = null && networkinfo.isavailable ()) {
toast.maketext (context, " connected network ! ",toast.length_short). Show ();
} else {
toast.maketext (Context, "The Current network is not available ! ",toast.length_short). Show ();
}
}
}
}
Also be sure to configureNetwork-related permissions, here you need to add the following code to the Androidmanifest.xml:
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
This means allowing the program to access information about the GSM network.
Broadcast small case-monitoring System network status--android development