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.
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.
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?
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.
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.
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.
You can check this using process lifecycle owner.
fun isAppOnForeground(): Boolean {
return ProcessLifecycleOwner.get().getLifecycle().getCurrentState()
.isAtLeast(Lifecycle.State.STARTED);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With