Search code examples
androidservicebroadcastreceiver

Broadcast receiver not registered


I am having an error where I register a broadcast receiver in the constructor. However, when I unregister it in onPause it throws an exception about not being registered. How can this be and can you help me solve the problem.

The main problem is that I am bound to a NetworkService class, which I also can't unbind from. It gives problems when I restart the app and says that I have a "leak". But I don't know which of the two problems generating the leak.

Here is my code:

Constants

private static NetworkService networkService;
private ServiceConnection networkServiceConnection;
private BroadcastReceiver networkServiceMessageReceiver;
private boolean boundToService;

OnCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    /** Defines callbacks for service binding, passed to bindService() */
    networkServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            NetworkService.LocalBinder binder = (NetworkService.LocalBinder) service;
            networkService = binder.getService();
            boundToService = true;

            LocalBroadcastManager.getInstance(SplashActivity.this).registerReceiver(networkServiceMessageReceiver, new IntentFilter(NetworkService.CHECK_FOR_UPDATE_RESULT));
            checkForUpdate();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            boundToService = false;
        }
    };
}

OnResume

@Override
protected void onResume() {
    super.onResume();

    //Bind to NetworkService
    if(!boundToService)
    {
        Intent intent = new Intent(this, NetworkService.class);
        bindService(intent, networkServiceConnection, Context.BIND_AUTO_CREATE);
    }
}

OnPause

@Override
protected void onPause() {
    super.onPause();

    unregisterReceiver(networkServiceMessageReceiver);
}

OnStop

@Override
protected void onStop() {
    super.onStop();

    unbindService(networkServiceConnection);
}

Solution

  • You are calling unregisterReceiver() on the Activity context, but you are calling registerReceiver() on the LocalBroadcastManager context. This can't work. You need to register and unregister on the same Context.

    Make sure you only unregister if your Service has already been bound, otherwise you won't have called register().

    Also, since you are unregistering in onPause() you need to reregister in onResume().