Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if my application is in foreground or background, android?

I need to check if my application is running in background or foreground and then perform some operations relatively to it.

I searched a lot and a clear solution is not available.

  1. Make a parent activity in its onPause() and onResume() methods keep some variable to update them accordingly. When you create any new activity inherit your parent activity. Although this is the best solution I feel to achieve my task, but sometimes if the power button is clicked even though application is in background, it's onResume() is invoked.

  2. Use GETTASKS permission - This solution is also good. But it can only used for debug purpose. Not if you want to put your app on Google Play Store.

Get Running Taks

Any other preferred solution for this?

like image 895
WISHY Avatar asked Nov 12 '14 05:11

WISHY


People also ask

How do I know if an app is running in the background or foreground?

It's very easy to detect when an Activity goes background/foreground just by listening to the lifecycle events, onStop() and onStart() of that Activity.

How do you tell if an app is running in the background Android?

If you don't want the app to relaunch when you restart your phone, tap Uninstall to remove the app. To see what apps are running in the background, go to Settings > Developer Options > Running Services.

How do I know if app is on in background?

Just check if the number of stopped activities is equal to the number of started activities. If they're equal, your application is being backgrounded. If there are more started activities, your application is still visible.


1 Answers

You can check this using process lifecycle owner.

fun isAppOnForeground(): Boolean {
return ProcessLifecycleOwner.get().getLifecycle().getCurrentState()
    .isAtLeast(Lifecycle.State.STARTED);
}
like image 148
Tushar Pingale Avatar answered Nov 15 '22 17:11

Tushar Pingale