Measuring time spent on Android apps

I am new to android. In my application, I want to track how much time other applications (which are installed on the device) are used (in the foreground).

Is it possible? If so, how?

Thanks in advance!

+7
source share
2 answers

The first thing to know here is that applications that run in the foreground:

You can detect the foreground / background application currently with an ActivityManager.getRunningAppProcesses() call.

So it will look something like this:

  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 also check this out: Defining foreground / background processes .

To measure the time taken to complete a process, you can use this method:

 getElapsedCpuTime() 

See the article.

+4
source

I think the only way to do this is with the help of the background service and the continuous search for the application in the foreground (possibly with the ActivityManager).

But this solution is expensive in battery

+2
source

All Articles