I have a need to create a custom broadcast receiver in the onCreate event of an activity and obviously I need to unRegister the broadcast receiver in the onDestroy event of the activity
For clarity this is a snippet of the code I use
public class AnActivity extends Activity { private ResponseReceiver receiver; public class ResponseReceiver extends BroadcastReceiver { public static final String ACTION_RESP = "mypackagename.intent.action.MESSAGE_PROCESSED"; @Override public void onReceive(Context context, Intent intent) { // TODO Start a dialogue if message indicates successfully posted to server } } /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP); filter.addCategory(Intent.CATEGORY_DEFAULT); receiver = new ResponseReceiver(); registerReceiver(receiver, filter); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); }
I have read that onPause/onResume and onStart/onStop events for the activity should also register and unregister the broadcast receiver.
I'm really wanting to understand what is considered to be the best practice for this and why.
You should register and unregister your broadcast in onResume() and onPause() methods. if you register in onStart() and unregister it in onStop().
BroadcastReceiver) . Be sure to unregister the receiver when you no longer need it or the context is no longer valid.
Registering Broadcast Receiver An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest. xml file.
The onReceiver() method is first called on the registered Broadcast Receivers when any event occurs. The intent object is passed with all the additional data. A Context object is also available and is used to start an activity or service using context.
You should register and unregister your receivers onStart()
and onStop()
.
The only reason an Activity would register BroadcastReceiver
s 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.
If you want to receive broadcast events in the background you should consider using a service as indicated here.
Like Konstantin says, onDestroy()
is not guaranteed to be called, and you could continue receiving broadcasts for a long time, when the Activity
is no longer open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With