Broadcastreceiver to detect network is connected

前端 未结 6 1760
情书的邮戳
情书的邮戳 2020-12-05 02:36

I\'m trying to get the moment where user connects to a network, then I thought a BroadcastReceiver is a good approach... The thing that I would like to do is, w

6条回答
  •  难免孤独
    2020-12-05 03:25

    I tried this approach (below) and it worked. Not yet fully tested, but I use similar for receiving battery status. This way there is less code and it does the job.

    private BroadcastReceiver networkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.CONNECTED) {
                    Log.d(LOG_TAG, "We have internet connection. Good to go.");
                } else if (networkInfo != null && networkInfo.getDetailedState() == NetworkInfo.DetailedState.DISCONNECTED) {
                    Log.d(LOG_TAG, "We have lost internet connection");
                }
            }
        }
    };
    
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkReceiver, intentFilter);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        if (networkReceiver != null)
            unregisterReceiver(networkReceiver);
    }
    

提交回复
热议问题