監控Android 上的網路狀態變化
問題:如何偵測Android 上網路狀態的變化設備,特別是網路離線時?
為了捕捉網路狀態變化,Android 提供了 BroadcastReceiver 類別。 ConnectivityManager 類別可讓您取得活動網路連線的資訊。
解決方案:
1.建立一個擴充 BroadcastReceiver
<code class="java">public class ConnectionChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (activeNetInfo != null) { Toast.makeText(context, "Active Network Type: " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT).show(); } if (mobNetInfo != null) { Toast.makeText(context, "Mobile Network Type: " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT).show(); } } }</code>
2 的 Java 類。在AndroidManifest.xml中加入必要的權限
<code class="xml"><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /></code>
3.在AndroidManifest.xml中註冊BroadcastReceiver
<code class="xml"><receiver android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver" android:label="NetworkConnection"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver></code>
4.動態註冊BroadcastReceiver(可選)
如果您需要在程式碼中動態註冊BroadcastReceiver,您可以使用以下方法:<code class="java">BroadcastReceiver receiver = new ConnectionChangeReceiver(); IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"); context.registerReceiver(receiver, filter);</code>
以上是如何在 Android 上偵測網路狀態變化和離線事件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!