Handling Internet Connectivity Changes in Android
The question centers on the need for a Broadcast Receiver that can monitor changes in internet connectivity, as the existing code only detects connectivity changes.
To address this, here's an alternative approach:
<code class="java">public class NetworkUtil { public static final int TYPE_WIFI = 1; public static final int TYPE_MOBILE = 2; public static final int TYPE_NOT_CONNECTED = 0; public static int getConnectivityStatus(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) return TYPE_WIFI; if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) return TYPE_MOBILE; } return TYPE_NOT_CONNECTED; } }</code>
This method determines if the device is connected to WiFi or mobile data.
<code class="java">public class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(final Context context, final Intent intent) { int status = NetworkUtil.getConnectivityStatus(context); if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction()) { if (status == NetworkUtil.TYPE_NOT_CONNECTED) { // Handle loss of internet connectivity } else { // Handle restoration of internet connectivity } } } }</code>
This BroadcastReceiver monitors connectivity state changes and triggers actions based on the current status. Remember to include the appropriate permissions and register the receiver in your 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>
The above is the detailed content of How to Handle Internet Connectivity Changes in Android?. For more information, please follow other related articles on the PHP Chinese website!