Reputation: 2457
I am new to android. In my application, i want to track for how much time other applications (which are installed on device) are used (in foreground).
Is it possible? If yes then how?
Thanks in advance!
Upvotes: 7
Views: 3653
Reputation: 5585
First thing , that's required to be known here is what are the applications that are running in the foreground :
You can detect currently foreground/background application with ActivityManager.getRunningAppProcesses()
call.
So, it will look something like ::
class findForeGroundProcesses extends AsyncTask<Context, Void, Boolean> {
@Override
protected Boolean doInBackground(Context... params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
// Now you call this like:
boolean foreground = new findForeGroundProcesses().execute(context).get();
You can probably check this out as well : Determining foreground/background processes.
To measure the time taken by a process to run its due course , you can use this method :
getElapsedCpuTime()
Refer this article .
Upvotes: 4
Reputation: 1222
I think that the only way to do this it's by using a background service and continuously searching which app is in foreground (it's possible by using ActivityManager).
But this solution is costly in battery
Upvotes: 3