Search code examples
javaandroidbroadcastreceiverandroid-service

Not able to stop Service when Broadcast Receiver is registered in Service


I am having a BroadcastReceiver in a Service.

I am registering receiver in service's oncreate() method like,

final MyReceiver myReceiver = new MyReceiver();
@Override
public void onCreate() {
    IntentFilter filter = new IntentFilter(SOME_FILTER);
    registerReceiver(myReceiver, filter);
}

Then I have created a method to unregister receiver and stop service like,

public void stopService(){
    if(myReceiver != null){
        try{
            unregisterReceiver(myReceiver);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    stopSelf();
}

But it does not stop the service. There is no exception, no error. Simply the service doesn't stop.

I have also tried it following way,

public void stopService(){
    if(myReceiver != null){
        try{
            unregisterReceiver(myReceiver);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    stopForeground(true);
    stopSelf();
}

By doing this the Notification of Service being run in foreground hides but service's onDestroy() is not being called.

I also tried to put the code to unregister receiver in onDestroy() but after calling stopSelf() method onDestroy() is never called.

If I don't register the BroadcastReceiver in the service, everything works perfectly fine, service stops and onDestroy() gets called but when I register receiver then it doesn't stop.

Any ideas what's going on here?

Edit

This is how I am binding and starting the service

Intent serviceIntent = new Intent(MainActivity.this, MyService.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
startService(serviceIntent);

And this is mConnection

MyService myService;

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service){
        LocalBinder binder = (LocalBinder) service;
        myService = binder.getService();
        isBound = true;
    }
    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        isBound = false;
    }
};

Below is how I am unbinding the service and stopping it.

if(isBound){
    unbindService(mConnection);
    isBound = false;
}

myService.stopService();
myService = null;

Solution

  • Just found a solution of the same by hit and trial method.

    I shifted the code to unregister the receiver in onDestroy() method and all worked.

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(myReceiver != null){
            try{
                unregisterReceiver(myReceiver);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    

    I think problem was occurring because I was trying to unregister the receiver before stopping the service.