7

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!

Unnati
  • 2,441
  • 17
  • 37
  • 2
    Check if [this](http://stackoverflow.com/questions/6064137/can-an-android-application-know-when-another-android-application-is-running) link may help you. – HemChe May 06 '13 at 11:39
  • click the word this... it's a hyperlink :) – HemChe May 06 '13 at 11:41

2 Answers2

4

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 .

Community
  • 1
  • 1
The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
3

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

nbe_42
  • 1,212
  • 1
  • 14
  • 22