我需要在一个活动的onCreate事件中创建一个自定义广播接收器,显然我需要在活动的onDestroy事件中取消注册广播接收器。
为了清晰起见,这是我使用的代码片段
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);
}
我读过在活动的onPause/onResume和onStart/onStop事件中应该注册和取消注册广播接收器。
我真的很想了解什么被认为是最佳实践以及为什么。
onDestroy()
被调用时,接收者将不再监听任何事件。 - billa-code