Marian Pavel
Marian Pavel

Reputation: 2886

BroadcastReceiver to check if any network change occurs

I understand that if I want to check my internet connection in a Activity everytime network state changes I have to create a BroadcastReceiver.

I have added the permission to my manifest and I have created the following class:

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            Log.d("Netowk Available ", "Flag No 1");
        }
        else
        {
            Log.d("Network not Available","Network is not available");
        }
    }
}

The only think I don't understand is how do I make the listener to see the changes. I have Overrided the onResume and onPause in my activity but nothing happens:

@Override
public void onResume() {
    super.onResume();  // Always call the superclass method first

    registerReceiver(myBroadcast, new IntentFilter());
}

@Override
public void onPause() {
    super.onPause();  // Always call the superclass method first

    unregisterReceiver(myBroadcast);
}

Upvotes: 1

Views: 675

Answers (1)

dinostroza
dinostroza

Reputation: 103

You have to put the BroadcastReceiver inside your Activity, like this answer points out: https://stackoverflow.com/a/4011057/1758048

  • I'd put this in a comment but I still haven't enough reputation points :(

Regards.

Upvotes: 3

Related Questions