靜態註冊廣播監聽網路變化
阿新 • • 發佈:2019-02-18
常用的IM聊天App中都會判斷網路連線是否可用,今天我們就用靜態註冊註冊廣播來監聽網路的變化:首先申請網路許可權
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
然後在mainifest檔案靜態註冊廣播:
<receiver android:name=".NetWorkChangeReceiver" android:enabled="true" android:exported="true"> <intent-filter android:priority="1000"> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter> </receiver>
這樣當網路變化的時候,就能監聽到相應的網路情況:
OK了,靜註冊廣播監聽網路變化已實現。package com.example.administrator.broadcastreceiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; public class NetWorkChangeReceiver extends BroadcastReceiver { public NetWorkChangeReceiver() { } @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving //Toast.makeText(context,"netChanged!",Toast.LENGTH_LONG).show(); ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if(networkInfo !=null && networkInfo.isAvailable()) { Toast.makeText(context,"isAvailable!",Toast.LENGTH_LONG).show(); }else { Toast.makeText(context,"unAvailable!",Toast.LENGTH_LONG).show(); } } }