解决方法
首先,这里需要知道的是前台运行的应用程序是什么:
您可以使用ActivityManager.getRunningAppProcesses()调用检测当前的前台/后台应用程序.
所以,它看起来像::
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();
您也可以查看一下:Determining foreground/background processes.
要测量进程运行其到期时间所花费的时间,您可以使用此方法:
getElapsedcpuTime()
请参阅此article.