在Android 中監控網路連線
問題:
如何監控網路變化Android上的連接並捕獲網路中斷事件?
答案:
要在 Android 中捕獲網路中斷事件,請按照以下步驟操作:
1。建立廣播接收器:
建立一個擴充BroadcastReceiver 類別的新Java 類別:
<code class="java">public class ConnectionChangeReceiver extends BroadcastReceiver { @Override public void onReceive( Context context, Intent intent ) { // Network connectivity change handling code goes here } }</code>
2.註冊廣播接收器:
將以下XML 程式碼加入
<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>
3。授予權限:
將下列權限加入
<code class="xml"><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/></code>
4。處理網路連線變更:
在 ConnectionChangeReceiver 類別的 onReceive 方法中,您可以處理網路連線變更。例如,您可以使用下列指令檢查活動網路和行動網路資訊:
<code class="java">ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE ); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE );</code>
範例程式碼:
<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>
以上是如何偵測和處理 Android 中的網路連線變化?的詳細內容。更多資訊請關注PHP中文網其他相關文章!