Android 判断 Activity 是否在前台

先得到 TopTask

protected ActivityManager mActivityManager;

mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);

    public ActivityManager.RunningTaskInfo getTopTask() {
        List tasks = mActivityManager.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            return tasks.get(0);
        }

        return null;
    }

再判断 Activity 是不是在栈的最上面

    public boolean isTopActivity(
            ActivityManager.RunningTaskInfo topTask,
            String packageName,
            String activityName) {
        if (topTask != null) {
            ComponentName topActivity = topTask.topActivity;

            if (topActivity.getPackageName().equals(packageName) &&
                    topActivity.getClassName().equals(activityName)) {
                return true;
            }
        }

        return false;
    }

举个例子

    public void yourMethod() {
        if (isTopActivity(getTopTask(), yourPackageName, yourActivityName)) {
            //
        } else {
            //
        }
    }

你可能感兴趣的:(Android 判断 Activity 是否在前台)