Lorsque pour annuler l'inscription de BroadcastReceiver? Dans onPause(), onDestroy(), ou onStop()?

Quand dois-je utiliser unregisterReceiver? Dans onPause(), onDestroy(), ou onStop()?

Note: j'ai besoin de ces services pour s'exécuter en arrière-plan.

Mise à jour:

  1. J'obtiens une exception libérant des récepteurs null.

  2. Activité a fui l'intention des récepteurs de vous manquent appel à unregisterReceiver();

Veuillez me dire si il ya quelque chose de mal, voici mon code:

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());
}
}
  • Tout d'abord, vous ne jamais avoir à appeler les méthodes de cycle de vie comme onPause(), onDestroy() ou onStop().
  • Quel est le comportement attendu de votre application? Tous les cas mentionnés ci-dessus sont valables, tout dépend de votre cas d'utilisation
InformationsquelleAutor Muhammad | 2014-01-15