Android判断当前应用是否前台应用

使用RunningAppProcessInfo来轮询判断,其中魅族手机遇到一个问题,其返回的状态值和其他手机不一样,做了下兼容:

    private boolean isAppBackground() {
        boolean isInBackground = true;
        String processName = "empty";
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo appProcess : runningProcesses) {
                if (appProcess.processName.equals(getPackageName())) {
                    processName = appProcess.processName;
                    Global.debug("-===1122====="+processName);
                    Global.debug("-===11223====="+appProcess.importance);

                    if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                        isInBackground = true;
                    } else if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE_PRE_26) {
                        isInBackground = true;
                    } else {
                        isInBackground = false;
                    }
                }

            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(getPackageName())) {
                isInBackground = false;
            }
            Global.debug(componentInfo.getPackageName()+"==2==");
        }
        return isInBackground;
    }

AndroidProcess的五种状态

Foreground 当前进程正在运行,可以接受触点

Visible      当前进程正在运行,但是其他一些界面显示在它之上,但是它是可见的

Service     当前进程包含服务正在运行

Background 当前进程在后台运行

Empty      当前是空进程

Android源码文档中解释

IMPORTANCE_BACKGROUND

this process process contains background code that is expendable.

IMPORTANCE_EMPTY

this process is empty of any actively running code.

IMPORTANCE_FOREGROUND

this process is running the foreground UI.

IMPORTANCE_SERVICE

this process is contains services that should remain running.

IMPORTANCE_VISIBLE

this process is running something that is actively visible to the user, though not in the immediate foreground.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值