17

I want to check to see if an activity is running or finished. Is there any method through which I can check the status of activity?

I found activity.isFinishing() but I am not sure about it.

harry_p_6
  • 31
  • 8

3 Answers3

21

If you want to perform any step before Activity is going to become invisible.

Their are several choices here.

onDestroy() - for final cleanup.

isFinishing() - right after act.finish() is called it will return true.

onStop() - when the Activity is killed by framework process. (not destroyed)

onPause() - when the Activity is covered by any other Activity

onBackPressed() - capturing the event of hardware Back key triggered by user.

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
  • 10
    There is also `isDestoyed()` (added in API 17) http://developer.android.com/reference/android/app/Activity.html#isDestroyed%28%29 – Jared Rummler Sep 05 '15 at 07:46
  • Yes, it was released later, so that's why its not included in the answer. Thanks for mentioning. – Adil Soomro Sep 05 '15 at 10:33
  • I think the expression 'killed' can cause some confusion. For example, `onStop()` is called when another application comes to the foreground. But the Activity's state is maintained, so it's not killed :) – starriet Feb 05 '21 at 16:09
6

Call isFinishing in the onPause method before the activity is destroyed:

@Override
protected void onPause() {
    super.onPause();
    if (isFinishing()) {
        // Here  you can be sure the Activity will be destroyed eventually
    }
}
live-love
  • 48,840
  • 22
  • 240
  • 204
0

I realize this is very old, but for anyone using Kotlin:

We can check within a Fragment:

// FRAGMENT
override fun onPause() {
    super.onPause()
    // Log.v(TAG, "onPause");
    if(requireActivity().isChangingConfigurations) {
         // Config change
    } else {
        if(requireActivity().isFinishing) {
            // deal with activity ending (finish up viewModel etc)
        }
        // deal with rotate or other config changes as required
    }
}

Of course, we can also just do this directly inside an activity (just remove the requireActivity() parts).

David
  • 1,050
  • 1
  • 16
  • 31