在Android 5.0之前版本:
通过RunningTaskInfo类判断(需要额外权限):
/** *判断当前应用程序处于前台还是后台 */public static boolean isApplicationBroughtToBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; }
需要在AndroidMenitfest.xml文件中添加以下权限
<uses-permission android:name="android.permission.GET_TASKS" />
在Android 5.0 之后由于getRunningTask()方法被废弃,失效了所以在5.0之后我们用另外一种方法:
通过RunningAppProcessInfo类判断(不需要额外权限):
public static boolean isBackground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();for (RunningAppProcessInfo appProcess : appProcesses) { if (appProcess.processName.equals(context.getPackageName())) { if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) { Log.e("后台", appProcess.processName); return true; }else{ Log.e("前台", appProcess.processName); return false; } } }return false;
}
为了适配手机,我们可以写一个适配方法,从而适配系统:
private boolean isAppIsInBackground(Context context) {
boolean isInBackground = true; ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) { //前台程序 if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { for (String activeProcess : processInfo.pkgList) { if (activeProcess.equals(context.getPackageName())) { isInBackground = false; } } } } } else { List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1); ComponentName componentInfo = taskInfo.get(0).topActivity; if (componentInfo.getPackageName().equals(context.getPackageName())) { isInBackground = false; } } return isInBackground;
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦