【发布时间】:2014-02-03 20:46:14
【问题描述】:
什么时候应该使用 unregisterReceiver?在onPause()、onDestroy() 或onStop()?
注意:我需要服务在后台运行。
更新:
我得到一个异常释放接收器
null。Activity 已泄露 Intent 接收器,您是否错过了对
unregisterReceiver();的调用
如果有问题请告诉我,这是我的代码:
private boolean processedObstacleReceiverStarted;
private boolean mainNotificationReceiverStarted;
protected void onResume() {
super.onResume();
try {
registerReceivers();
} catch (Exception e) {
Log.e(MatabbatManager.TAG,
"MAINActivity: could not register receiver for Matanbbat Action "
+ e.getMessage());
}
}
private void registerReceivers() {
if (!mainNotificationReceiverStarted) {
mainNotificationReceiver = new MainNotificationReceiver();
IntentFilter notificationIntent = new IntentFilter();
notificationIntent
.addAction(MatabbatManager.MATABAT_LOCATION_ACTION);
notificationIntent
.addAction(MatabbatManager.MATABAT_New_DATA_RECEIVED);
notificationIntent
.addAction(MatabbatManager.STATUS_NOTIFCATION_ACTION);
registerReceiver(mainNotificationReceiver, notificationIntent);
mainNotificationReceiverStarted = true;
}
if (!processedObstacleReceiverStarted) {
processedObstacleReceiver = new ProcessedObstacleReceiver();
registerReceiver(processedObstacleReceiver, new IntentFilter(
MatabbatManager.MATABAT_ALARM_LOCATION_ACTION));
processedObstacleReceiverStarted = true;
}
}
private void unRegisterReceivers() {
if (mainNotificationReceiverStarted) {
unregisterReceiver(mainNotificationReceiver);
mainNotificationReceiverStarted = false;
}
if (processedObstacleReceiverStarted) {
unregisterReceiver(processedObstacleReceiver);
processedObstacleReceiverStarted = false;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
unRegisterReceivers();
mWakeLock.release();//keep screen on
} catch (Exception e) {
Log.e(MatabbatManager.TAG, getClass() + " Releasing receivers-" + e.getMessage());
}
}
【问题讨论】:
-
首先,您永远不必调用诸如 onPause()、onDestroy() 或 onStop() 之类的生命周期方法。
-
您的应用程序的预期行为是什么?上面提到的所有情况都是有效的,这一切都取决于你的用例
标签: android broadcastreceiver intentservice