4

I know I can use isFinishing() in onPause() to know whether an activity is going to be killed by finish().

Then, how can I know an activity is going to be killed by OS temporarily due to low memory?

Thanks.

Kai
  • 3,775
  • 10
  • 39
  • 54

2 Answers2

2

Per the docs, onDestroy should be called right before the Activity is destroyed, regardless of the reason. If the finish was requested, isFinishing will return true. So if it is false, you can assume that the system needed to finish.

However, as the docs also say

Note: do not count on this method being called as a place for saving data!

In general, you cannot guarantee that your Activity will be killed nicely. Things like task killers mess with the lifecycle.

Use onPause or onSaveInstanceState to save things properly.

Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82
  • See this doc, http://developer.android.com/reference/android/app/Activity.html#isFinishing%28%29. Check to see whether this activity is in the process of finishing, either because you called finish() on it or someone else has requested that it finished. This is often used in onPause() to determine whether the activity is simply pausing or completely finishing. isFinishing() is also true, if the OS is killing the activity. Am I right? – Kai Mar 08 '11 at 00:33
  • 1
    I read that to mean it would not be true if the OS is killing it, but I haven't actually tested it myself. Why do you need to know if the OS is killing it? – Cheryl Simon Mar 08 '11 at 00:40
2

You cannot.

It's possible your activity could go away without the rest of your app going way, in this case onDestroy would be called. However it's also possible that your whole app is going to get killed at once, this like a kill -9 in unix. Your app cannot run any code at this time, it's killed instantly and without warning.

To handle this properly, you want to design your app to save all vital information to disk in onPause and be ready to retrieve it later in onCreate if needed.

Kevin TeslaCoil
  • 10,037
  • 1
  • 39
  • 33
  • 1
    It looks like Android only kill processes not individual activities. See discussion at http://stackoverflow.com/questions/5227071/understanding-of-isfinishing – Kai Mar 08 '11 at 18:30
  • It's not an "only" thing. If your code relies on Android only killing processes (the app), it's wrong. If your code relies on Android only killing Activities, it's wrong. Handle either. – Kevin TeslaCoil Apr 04 '11 at 04:04