Android 中的Internet 連線變更偵聽器
連線變更的預設廣播接收器監視網路可用性,但不一定會監視Internet 連線。為了解決這個限制,讓我們探索更全面的方法。
網際網路連線監控
利用下列公用程式類別來決定目前的網路連線狀態:
<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>
用於網路連線更改的廣播接收器
建立偵聽Internet 連接變更的廣播接收器:
<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 設定
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中文網其他相關文章!