0

I am using a BroadcastReceiver to detect changes in the network. However, my else statement executes twice when there is no internet connection. What is a better way to handle this?

@Override
public void onReceive(Context context, Intent intent) {

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();

    if (activeNetwork != null && (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)) {
        Toast.makeText(context, "Connected", Toast.LENGTH_LONG).show();
    } else  {
        Intent i = new Intent(context, NetworkErrorActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}
safaiyeh
  • 1,655
  • 3
  • 16
  • 35

1 Answers1

0

I think you should use this method activeNetworkInfo.isConnected(). This returns a boolean value true when connected.