This is the implementation method for the old Android API (Android 7 and earlier), using BroadcastReceiver +
ConnectivityManager+NetworkInfoto detect network connection and disconnection.
1. Core Knowledge Points
- ConnectivityManager: A system service class dedicated to managing network connection status.
- Permissions: You need to add the network state permission in
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Code language: HTML, XML (xml)
- Principle: When network changes occur, the system sends network broadcasts. Inside the
onReceivecallback ofBroadcastReceiver, useConnectivityManagerto retrieve current network information and determine whether the network is connected or disconnected.
2. Complete onReceive Code
public void onReceive(Context context, Intent intent) {
// Obtain network management system service
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// Get current active network information (deprecated API)
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
if (networkInfo.isAvailable()) {
Toast.makeText(context, "Network Connected", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Network Disconnected", Toast.LENGTH_LONG).show();
}
} else {
// networkInfo is null, meaning no network
Toast.makeText(context, "Network Disconnected", Toast.LENGTH_LONG).show();
}
}
Code language: JavaScript (javascript)
3. Important Notice (Deprecation)
getActiveNetworkInfo() and NetworkInfo have been deprecated starting from Android 10 (API29)
Newer Android versions recommend using the
ConnectivityManager.NetworkCallbackcallback method to monitor networks. The old broadcast + NetworkInfo approach is no longer recommended.
Drawbacks of the Old Method
- After Android 8.0 (API26), statically registered network state broadcasts are restricted. Static registration cannot receive network change broadcasts; you must dynamically register the receiver.
- The
NetworkInfoclass is deprecated. Direct calls on newer Android versions will trigger warnings or even fail.
4. Dynamically Register Broadcast Receiver
// Define broadcast receiver
public class NetReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Paste the network detection code above here
}
}
// Dynamic registration inside Activity
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
NetReceiver receiver = new NetReceiver();
registerReceiver(receiver, filter);
Code language: PHP (php)
Android Network Connectivity / Disconnection Broadcast Listener