android 如何判断应用是否处于前台?

答:可以通过ActivityManager获取运行的任务栈进行判断,具体判断如下

ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
List runningTaskInfos = activityManager.getRunningTasks(Integer.MAX_VALUE);
        if (runningTaskInfos != null && runningTaskInfos.size() > 0) {
            String topPackageName = runningTaskInfos.get(0).topActivity.getPackageName();//获取顶部的activity,也可以进行遍历判断是否处于后台
            if("需要判断的PackageName".equals(topPackageName))
        }

发表评论

CAPTCHAis initialing...