我的活动方式是
class MainActivity extends Activity{
onCreate(bundleInstnace){
super.onCreate(bundleInstnace);
//IntentFilter intentFilter with some actions
registerReceiver(myReceiver, intentFilter);
}
onDestroy(){
super.onDestroy();
try{
unregisterReceiver(myReceiver)
}catch(Exception e){}
}
final Receiver myReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
//functionality based on actions
}
}
}
即使我在onDestroy()中取消注册myReceiver,即使在调用onDestroy之后,仍然可以接收广播接收器。我尝试在onStart()中注册并在onStop()中取消注册但仍然相同。你能帮我准确地告诉我我失踪的地方。问题的发生是随机的..
答案 0 :(得分:0)
取消注册接收方后调用super.onDestroy();
。 (虽然不建议使用onDestroy
,因为无法保证调用它。请改用onStop
。)
onDestroy(){
try{
unregisterReceiver(myReceiver)
}catch(Exception e){}
super.onDestroy();
}
答案 1 :(得分:0)
您应该在 onResume 中注册接收者,并在 onPause 中取消注册:
@Override
protected void onResume() {
super.onResume();
registerReceiver(myReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
try {
unregisterReceiver(myReceiver);
} catch (IllegalArgumentException e) {
// Log here or ignore
}
}