1

In Activity, I register receiver in onCreate and unregister it onDestroy. It should works fine if every onCreate is followed by onDestroy after the next onCreate. Otherwise, if onCreate is being called more than onDestroy, receiver is registered multiple time and the app mis-behaves.

So my questions are:

  1. Is that ok I register receiver in onCreate and unregister it in onDestroy?
  2. Is that onCreate is always followed by onDestroy before next onCreate?
Bear
  • 5,138
  • 5
  • 50
  • 80

2 Answers2

2

onDestroy is not guaranteed to be called:

http://developer.android.com/reference/android/app/Activity.html#onDestroy%28%29

"

protected void onDestroy ()

Added in API level 1 Perform any final cleanup before an activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here. This method is usually implemented to free resources like threads that are associated with an activity, so that a destroyed activity does not leave such things around while the rest of its application is still running. There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.

Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

"

You may also want to look at this thread:

Activity OnDestroy never called?

Community
  • 1
  • 1
mastDrinkNimbuPani
  • 1,249
  • 11
  • 14
1

onDestroy is called when the activity is being destroyed. Or removed from the back stack, when ever the user doesn't want it or there is no possible way to get back to it. When your activity wants to receive a broadcast that is fine to do it how you are. If there are no dialogs appearing or notifications or toasts appearing after you receive that should be fine also, if you want to be on the real safe side and only have one activity receiving at a time, and only while the activity is visible move these to onResume and onPause.

You could probably some how unregister when another activity has been brought to the front and re-register after?

FabianCook
  • 20,269
  • 16
  • 67
  • 115