Measure Time Spent on Android Applications

前端 未结 2 1823
天命终不由人
天命终不由人 2021-01-05 06:58

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 possibl

相关标签:
2条回答
  • 2021-01-05 07:09

    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 .

    0 讨论(0)
  • 2021-01-05 07:29

    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

    0 讨论(0)
提交回复
热议问题