11

May I know what is the proper way to know whether an Activity has been destroyed? Currently, I am using the following way.

private volatile boolean isOnDestroyCalled = false;

@Override
protected void onDestroy() {
    super.onDestroy();
    isOnDestroyCalled = true;
}

public boolean isOnDestroyCalled() {
    return this.isOnDestroyCalled;
}

Is there any other way better than the above?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875
  • I dont quite understand your problem, when do you want to know this?, are you destryoing the activity or is something else triggering the destroy? You can always trigger Finish(); to destroy it. Here is some help http://developer.android.com/reference/android/app/Activity.html – najk Jul 10 '12 at 08:54
  • 2
    I needed to know this myself because I had an async task that triggered a callback on the activity, which could have been destroyed in the mean time. My workaround was to keep a reference to the callback in the activity, a reference to the activity in the callback, and null out the ref in the callback when the activity was being destroyed so the callback does not perform anything if null. – qix Apr 25 '14 at 11:36
  • @Linus The best known technique so far is to use retained instance fragment : http://stackoverflow.com/questions/8417885/android-fragments-retaining-an-asynctask-during-screen-rotation-or-configuratio – Cheok Yan Cheng Apr 26 '14 at 02:19
  • Cool, that looks fine for dealing with configuration changes, but in my case the activity is never recreated (e.g. because the user hit back), and I just wanted to ignore the callback. – qix Apr 26 '14 at 17:57

1 Answers1

4

That will work, but sometimes the OS will go and shut your application down if it's inactive an amount of time when other applications need priority. For sure I know when that happens the variables will get nullified, not sure though if it would in your case using volatile which goes to main memory. But one way to be sure that you get the right value, is to save it in SharedPreferences.

Carnal
  • 21,744
  • 6
  • 60
  • 75