Broadcast receiver for checking internet connection in android app

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

    Add a broadcast receiver which can listen to network connectivity change. Then check wether device is connected to internet or not using ConnectivityManager. Refer to this post or video for detailed understanding. Below is the code:

    public class NetworkStateChangeReceiver extends BroadcastReceiver {
      public static final String NETWORK_AVAILABLE_ACTION = "com.ajit.singh.NetworkAvailable";
      public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";
    
      @Override
      public void onReceive(Context context, Intent intent) {
        Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
        networkStateIntent.putExtra(IS_NETWORK_AVAILABLE,  isConnectedToInternet(context));
        LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
      }
    
      private boolean isConnectedToInternet(Context context) {
        try {
          if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
          }
          return false;
        } catch (Exception e) {
          Log.e(NetworkStateChangeReceiver.class.getName(), e.getMessage());
          return false;
        }
      }
    }
    

    I wrote this receiver to show a notification on the Screen, that's why you see a local broadcast with the network status. Here is the code to show the notification.

    public class MainActivity extends AppCompatActivity {
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        IntentFilter intentFilter = new IntentFilter(NetworkStateChangeReceiver.NETWORK_AVAILABLE_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            boolean isNetworkAvailable = intent.getBooleanExtra(IS_NETWORK_AVAILABLE, false);
            String networkStatus = isNetworkAvailable ? "connected" : "disconnected";
    
            Snackbar.make(findViewById(R.id.activity_main), "Network Status: " + networkStatus, Snackbar.LENGTH_LONG).show();
          }
        }, intentFilter);
      }
    }
    

    Activity listens to the intent broadcasted by the network receiver and shows the notification on the screen.

提交回复
热议问题