Where to unregister BroadcastReceiver (in a service)? Where to unregister BroadcastReceiver (in a service)? android android

Where to unregister BroadcastReceiver (in a service)?


Try like this:

public class MyService extends Service {    BroadcastReceiver brSms;    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        brSms = new BroadcastReceiver() {            @Override            public void onReceive(Context context, Intent intent) {                //Do some  stuff            }        };        registerReceiver(brSms, new IntentFilter(SENT_SMS_ACTION));    }    @Override    public void onStart(Intent intent, int startid) {    }    @Override    public void onDestroy() {        unregisterReceiver(brSms);        Toast.makeText(this, "onDestroy has been called", Toast.LENGTH_SHORT).show();    }}


I don't know what's causing your error message, but to answer your question, you're doing it absolutely correctly to unregister in onDestroy(). I know from experience that this works well, and it's also a good place to do it according to the documentation for Service.onDestroy():

... The service should clean up any resources it holds (threads, registered receivers, etc) at this point. ...


Avoid onStart()... try onStartCommand(Intent intent, int flags, int startId)...