Android判断当前应用程序状态是在前台还是后台
2018-07-20 来源:open-open
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
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐