[android] 當wifi或3g網絡狀態改變時,BroadcastReceiver



Answers

這是我在連接發生變化時收到通知的方法。 您定義BroadCastReceiver以接收廣播。

public class NetworkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        boolean isConnected = wifi != null && wifi.isConnectedOrConnecting() ||
            mobile != null && mobile.isConnectedOrConnecting();
        if (isConnected) {
            Log.d("Network Available ", "YES");
        } else {
            Log.d("Network Available ", "NO");
        }
    }
}

您還必須在清單文件中定義BroadcastReceiver並按ConnectivityChange過濾。

<receiver android:name=".NetworkChangeReceiver" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
</receiver>

來源於here

Question

我有一個應用程序,只要手機連接到WiFi,它就會更新數據庫。 我已經實現了一個ServiceBroadcastReceiver來運行Service (它會告訴我正在使用什麼網絡),但問題是我不知道在manifest文件中添加什麼來在網絡狀態發生變化時啟動BroadcastReceiver它連接到某種網絡




補充@ Dantalian的答案。 從Android Nougat開始,您不應在您的Manifest上聲明您的接收器,因為它不會收到CONNECTIVITY_ACTION廣播。 您應該使用Context.registerReceiver(Receiver, Intent)方法註冊接收Context.registerReceiver(Receiver, Intent)

鏈接到here的來源




Related