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.
i had to figure out the right solution the hard way. the below code is part of cyanogenmod7 (the tablet tweaks) and is tested on android 2.3.3 / gingerbread.
methods:
this hopefully answers this issue in all extend (:
With regards to "2. How my background application can know what the application currently running in the foreground is."
Do NOT use the
getRunningAppProcesses()
method as this returns all sorts of system rubbish from my experience and you'll get multiple results which haveRunningAppProcessInfo.IMPORTANCE_FOREGROUND
. UsegetRunningTasks()
insteadThis is the code I use in my service to identify the current foreground application, its really easy:
Thats it, then you can easily access details of the foreground app/activity:
This requires an additional permission in activity menifest and works perfectly.
From lollipop onwards this got changed. Please find below code, before that user has to go Settings -> Security -> (Scroll down to last) Apps with usage access -> Give the permissions to our app
Taking into account that
getRunningTasks()
is deprecated andgetRunningAppProcesses()
is not reliable, I came to decision to combine 2 approaches mentioned in StackOverflow:In lollipop and up:
Add to mainfest:
And do something like this:
In order to determine the foreground application, you can use for detecting the foreground app, you can use https://github.com/ricvalerio/foregroundappchecker. It uses different methods depending on the android version of the device.
As for the service, the repo also provides the code you need for it. Essentially, let android studio create the service for you, and then onCreate add the snippet that uses the appChecker. You will need to request permission however.