There are two ways to register for broadcast:
- Dynamic registration: registering in code
- Static registration: register in Android manifest.xml
Idea: create a new class, let it inherit the BroadcastReceiver, and override the onReceiver() method of the parent class. When a broadcast arrives, the onReceive() method will be executed, and the specific logic can be processed in this method.
MainActivity code is as follows
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);
intentFilter = new IntentFilter();
//When the network status changes, the system issues a value of android.net.conn.connectivity'change broadcast
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//Dynamic registered broadcast receivers must be deregistered
unregisterReceiver(networkChangeReceiver);
}
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context,"newwork is unavailable",Toast.LENGTH_SHORT).show();
}
}
}
}
To access the network state of the system, you need to declare permissions
Add the following code to Android manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Run the code, press the Home key to return to the main interface (can't press the BACK key, otherwise the ondestore() method will execute), then open the Settings program - > data usage to enter the data usage details interface, and then switch the Cellular data button to start and disable the network, Toast will give a prompt.