1. 程式人生 > >Android判斷某個Activity是否正在前臺顯示

Android判斷某個Activity是否正在前臺顯示

判斷某個 Activity 是否正在前臺顯示的方法:

    /**
     * 判斷某個activity是否在前臺顯示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判斷某個介面是否在前臺,返回true,為顯示,否則不是
     */
    public static boolean isForeground(Activity context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

下面是呼叫:

                if (isForeground(activity)){
                    //在前臺顯示,做邏輯
                }