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.