Broadcast receiver for checking internet connection in android app

后端 未结 21 3189
温柔的废话
温柔的废话 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:51

    Use this method to check the network state:

    private void checkInternetConnection() {
    
        if (br == null) {
    
            br = new BroadcastReceiver() {
    
                @Override
                public void onReceive(Context context, Intent intent) {
    
                    Bundle extras = intent.getExtras();
    
                    NetworkInfo info = (NetworkInfo) extras
                            .getParcelable("networkInfo");
    
                    State state = info.getState();
                    Log.d("TEST Internet", info.toString() + " "
                            + state.toString());
    
                    if (state == State.CONNECTED) {
                          Toast.makeText(getApplicationContext(), "Internet connection is on", Toast.LENGTH_LONG).show();
    
                    } else {
                           Toast.makeText(getApplicationContext(), "Internet connection is Off", Toast.LENGTH_LONG).show();
                    }
    
                }
            };
    
            final IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver((BroadcastReceiver) br, intentFilter);
        }
    }
    

    remember to unregister service in onDestroy.

    Cheers!!

提交回复
热议问题