Internet Connectivity Change Listener in Android
The default Broadcast Receiver for connectivity changes monitors network availability but not necessarily Internet connectivity. To address this limitation, let's explore a more comprehensive approach.
Internet Connectivity Monitoring
Utilize the following utility class to determine the current Internet connection status:
<code class="java">public class NetworkUtil { public static int getConnectivityStatus(Context context) { // Check for active network ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); // Determine network type (Wi-Fi, mobile, or not connected) if (activeNetwork != null) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { return TYPE_WIFI; } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { return TYPE_MOBILE; } } return TYPE_NOT_CONNECTED; } // Convert network status to string representation (Wi-Fi, mobile, or not connected) public static int getConnectivityStatusString(Context context) { int conn = NetworkUtil.getConnectivityStatus(context); int status = 0; if (conn == NetworkUtil.TYPE_WIFI) { status = NETWORK_STATUS_WIFI; } else if (conn == NetworkUtil.TYPE_MOBILE) { status = NETWORK_STATUS_MOBILE; } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) { status = NETWORK_STATUS_NOT_CONNECTED; } return status; } }</code>
Broadcast Receiver for Internet Connectivity Changes
Create a Broadcast Receiver that listens for Internet connectivity changes:
<code class="java">public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { int status = NetworkUtil.getConnectivityStatusString(context); if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) { if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) { // Handle loss of Internet connection } else { // Handle recovery of Internet connection } } } }</code>
AndroidManifest.xml Configuration
Declare the Broadcast Receiver and necessary permissions in AndroidManifest.xml:
<code class="xml"><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <receiver android:name="NetworkChangeReceiver" android:label="NetworkChangeReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver></code>
By implementing this approach, you can monitor Internet connectivity changes and respond accordingly, ensuring the stability of web app functionality in scenarios with sudden loss of Internet connectivity.
The above is the detailed content of How can I create a reliable Internet connectivity change listener in Android?. For more information, please follow other related articles on the PHP Chinese website!