Search code examples
androidbroadcastreceiver

Broadcast receiver that listens to the network only works after exiting and restarting the app


I have a network broadcast receiver that listens to the network state and disables some actions when the device is disconnected to the internet, and enables them otherwise. The problem is it only works after exiting and restarting the app. On initial run, the app behaves the same even when the internet is cut off.

I made a class called NetworkStateReceiver:

public class NetworkStateReceiver extends BroadcastReceiver {

    public interface NetworkListener {
        void onNetworkAvailable();
        void onNetworkUnavailable();
    }

    private NetworkListener networkListener;

    public NetworkStateReceiver(NetworkListener networkListener) {
        this.networkListener = networkListener;
    }

    public void onReceive(Context context, Intent intent) {
        if (intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
            Log.d("app", "There's no network connectivity");
            networkListener.onNetworkUnavailable();
        } else {
            Log.i("app", "Network connected");
            networkListener.onNetworkAvailable();
        }
    }
}

I instantiate and register it on my MainActivity's onCreate:

networkStateReceiver = new NetworkStateReceiver(new NetworkStateReceiver.NetworkListener() {
    @Override
    public void onNetworkAvailable() {
        btnViewDiscoverFeed.setEnabled(true);
        btnViewExplore.setEnabled(true);
        btnViewNotification.setEnabled(true);
        btnViewUserProfile.setEnabled(true);
        setActiveFragment(activeFragment);
        viewPager.disableScroll(false);
    }

    @Override
    public void onNetworkUnavailable() {
        btnViewDiscoverFeed.setEnabled(false);
        btnViewExplore.setEnabled(false);
        btnViewNotification.setEnabled(false);
        btnViewUserProfile.setEnabled(false);
        setActiveFragment(2);
        viewPager.disableScroll(true);
    }
});
registerReceiver(networkStateReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

Then, I unregister it on the onDestroy:

@Override
public void onDestroy(){
    unregisterReceiver(networkStateReceiver);
    super.onDestroy();
}

Solution

  • Try once register and unregister methods in onStart(), onStop() respectively,

    The only reason an Activity would register BroadcastReceivers is to use the events in some way on the current activity, to inform the User of an event. If onStop() has been called, then the Activity is no longer in the foreground, and therefore cant update the User.but if you use onCreate() and OnDestroy, onDestroy() is not guaranteed to be called if the system kills your process in order to save memory. However, if the process is killed, the process won't be receiving broadcasts anyway

    onDestroy is not guaranteed to be called