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; } }
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.
The dark knight
source share