Fabian Zeindl
Fabian Zeindl

Reputation: 5988

Why is onDestroy() called after onResume() when using back-button

When I start my android-activity first onCreate() is called, then onResume().

When I then press the back-button to return to the home-screen and tap the app-icon again, first onCreate() is called, then onResume() and then onDestroy().

My app is still active then, but doing some action result in error since onDestroy() sets a few members to null.

Why is that?

Update: When I wait 30 seconds after pressing back everything works fine. I'm not doing anything heavy in onDestroy except setting a few variables to null and .interrupt()ing a background-thread.

Upvotes: 5

Views: 4203

Answers (4)

Fabian Zeindl
Fabian Zeindl

Reputation: 5988

Figured this out by myself. My understanding of what an Activity is was flawed. Of course Android calls onDestroy() on the old Activity instance, which can happen several seconds after the new one has been constructed.

Upvotes: 3

fdreger
fdreger

Reputation: 12495

I think there is something in addition to what you are describing. Android doesn't just keep activity from being destroyed, something MUST be happening on the main thread.

The symptoms sound exactly as if you had either:

  • a service doing a longish HTTP or database operation. Are you sure there are no suxg things?
  • another thread (perhaps managed by an AsyncTask?) calling a synchronized method

Upvotes: 0

Sagar Waghmare
Sagar Waghmare

Reputation: 4742

are you doing some heavy operations in onDestroy(). I think your activity view is destroyed, but not the activity object. And you tap on the App icon even before the previous Activity object is actually destroyed.

Upvotes: 0

Alexander
Alexander

Reputation: 48252

onDestroy gets called because, by default, pressing back key results in your activity calling finish() which initiates the destroying of the activity which calls onDestroy().

To prevent doing some action in case the activity is being destroyed do like this:

if(!isFinishing()) {
   // do your action here
}

isFinishing is a method of the Activity.

Upvotes: 0

Related Questions