Broadcast receiver for checking internet connection in android app

后端 未结 21 3210
温柔的废话
温柔的废话 2020-11-21 22:28

I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get

21条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 22:44

    just for someone else who wanna register a broadcast dynamicly:

    BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (checkWifiConnect()) {
                Log.d(TAG, "wifi has connected");
                // TODO
            }
        }
    };
    
    private void registerWifiReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mContext.registerReceiver(mWifiReceiver, filter);
    }
    
    private void unregisterWifiReceiver() {
        mContext.unregisterReceiver(mWifiReceiver);
    }
    
    private boolean checkWifiConnect() {
        ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null
                && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
                && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
    

提交回复
热议问题