Hello I am developing an application where I required to find time spent by user on a certain app like Facebook.
Whenever user has spent x minutes then I want to giv
As noted in the question Detect When other Application opened or Launched, you cannot listen for other applications launch signals, but you could sample the list of open applications every so often to check if the app you are looking for is a) running and b) in the foreground.
You would have to run this application as a service in the background, and I'm pretty sure that it could have devastating implications on the user's phone battery life.
You'll need a background Service
that will check the phone's activity (applications in foreground) and count their active/foreground elapsed time.
List foreground applications
<uses-permission android:name="android.permission.GET_TASKS" />
You can detect currently foreground application with ActivityManager.getRunningAppProcesses()
.
It will return a list of RunningAppProcessInfo
records.
To determine which application is on foreground check RunningAppProcessInfo.importance
== RunningAppProcessInfo.IMPORTANCE_FOREGROUND
.
How much time has been spent on it
Process.getElapsedCpuTime()
is the best to go IMHO.
Unfortunately I don't know how to get the Process
of another application...
So you could have a looping Service
incrementing spent time everytime an application is on foreground, but that would not be super precise I'm afraid.
Another way would be to control yourself the opening of those apps and when they leave it and come back to yours, evaluate the spent time in foreground at that moment.
Just some thoughts, I don't have a complete answer, sorry.