Search code examples
androidandroid-activitydialogactivity-finish

How to check if activity is in foreground or in visible background?


I have a splash screen on a timer. My problem is that before I finish() my activity I need to check that the next activity has started because a system dialogue box pops-up and I only want to finish(); once the user has selected an option from the dialogue box?

I know that there are many questions on how to see if your activity is in the foreground but I do not know if this allows for dialogue boxes on top of the activity too.

Here is the problem, the red is my activity which is in the background while the dialogue is in the foreground:

the red is my activity which is in the background while the dialogue is in the foreground

EDIT: I have tried just not using finish() but then my activity can be gone back to in the stack of applications which I am trying to avoid.


Solution

  • UPD: updated to state Lifecycle.State.RESUMED. Thanks to @htafoya for that.

    In 2019 with help of new support library 28+ or AndroidX you can simply use:

    val isActivityInForeground = activity.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)
    

    You can read more in the documenation to understand what happened under the hood.