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.
Any other preferred solution for this?
Original Answer : https://stackoverflow.com/a/60212452/10004454 The recommended way to do it in accordance with Android documentation is
In your gradle (app) add :
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
Then to check the state at runtime call
MyApplication().isActivityVisible()