I wish to have one application that runs in the background, which knows when any of the built-in applications (messaging, contacts, etc) is running.
So my questions are:
How I should run my application in the background.
How my background application can know what the application currently running in the foreground is.
Responses from folks with experience would be greatly appreciated.
For cases when we need to check from our own service/background-thread whether our app is in foreground or not. This is how I implemented it, and it works fine for me:
Now to check from other classes, whether app is in foreground or not, simply call:
This worked for me. But it gives only the main menu name. That is if user has opened Settings --> Bluetooth --> Device Name screen, RunningAppProcessInfo calls it as just Settings. Not able to drill down furthur
The ActivityManager class is the appropriate tool to see which processes are running.
To run in the background, you typically want to use a Service.
This is how I am checking if my app is in foreground. Note I am using AsyncTask as suggested by official Android documentation.`
`
and execute AsyncTask like this.
new CheckIfForeground().execute();
Do something like this:
I combined two solutions in one method and it works for me for API 24 and for API 21. Others I didn't test.
The code in Kotlin:
and in Manifest