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?
Well this solved my issue:
Use the following Function to check if your application is in Background or Foreground
Just want to use below code in Activity/Fragment:
Want to make one class like below:
If you want to check it after every one second then use below code in Activity:
And in onCreate() just call it once like:
use AppVisibilityDetector, I implement this class to detect the app visibility status. it can detect the foreground and background status and perform the callback method.
the MyApp is your Application class
you don't need add some other codes to your Activity or any permissions in the AndroidManifest.xml
check app is in forground state or background state
You can use this code to get the status of foreground(true) running of your app