简体   繁体   中英

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.

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM