處理Android 中的互聯網連接變化
問題集中在需要一個可以監視互聯網連接變化的廣播接收器,因為現有代碼僅檢測連接變更。
為了解決此問題,這裡有另一種方法:
<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>
此方法決定裝置是否連接到 WiFi 或行動數據。
<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>
此廣播接收器監視連線狀態變化並根據目前狀態觸發操作。請記得在 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>
以上是如何處理 Android 中的網路連線變更?的詳細內容。更多資訊請關注PHP中文網其他相關文章!