Add authority
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Create an instance of IntentFilter and add a value to it, action of "Android. Net. Conn.connectivity" change
When the network status changes, the system issues a broadcast with the value of android.net.connectivity'change. If the broadcast receiver wants to listen to any broadcast, add the corresponding action here.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); networkChangeReceiver = new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver,intentFilter); }
All dynamically registered broadcast receivers must be deregistered
@Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(networkChangeReceiver); }
Define an internal class NetworkChangeReceiver in MainActivity, inherit BroadcastReceiver, and override onReceive method, whenever the network changes
onReceive will execute
class NetworkChangeReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetworkInfo!=null && activeNetworkInfo.isAvailable()){ Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show(); } } }