清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>
1
public static boolean isBackground(Context context) { Log.d("Nat: isBackground.packageName1", context.getPackageName()); ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { Log.d("Nat: isBackground.processName", appProcess.processName); if (appProcess.processName.equals(context.getPackageName())) { Log.d("Nat: isBackground.importance", String.valueOf(appProcess.importance)); if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) { Log.i("后台", appProcess.processName); return true; }else{ Log.i("前台", appProcess.processName); return false; } } } return false; }
2
class ForegroundCheckTask 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<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses == null) { return false; } final String packageName = context.getPackageName(); Log.d("Nat: isAppOnForeground.packageName", context.getPackageName()); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { Log.d("Nat: isAppOnForeground.processName", appProcess.processName); if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) { return true; } } return false; } }
3
public static boolean isForeground(Context context) { Log.d("Nat: isBackground.checkPackageName", context.getPackageName()); ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> runningTasks = am.getRunningTasks(1); if (runningTasks != null){ // The first in the list of RunningTasks is always the foreground task. ActivityManager.RunningTaskInfo foregroundTaskInfo = runningTasks.get(0); String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName(); Log.d("Nat: isBackground.foregroundTaskPackageName", foregroundTaskPackageName); if (context.getPackageName().equals(foregroundTaskPackageName)){ return true; } // PackageManager pm = context.getPackageManager(); // PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0); // String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString(); } return false; }
4