activity堆栈式管理

activity堆栈式管理

代码示例:

public class ActivityManager {

    private static Stack activityStack = new Stack();

    private ActivityManager() {
    }

    /**
     * 获取指定的Activity
     */
    public static Activity getActivity(Class cls) {
        if (activityStack != null) {
            for (Activity activity : activityStack) {
                if (activity.getClass().equals(cls)) {
                    return activity;
                }
            }
        }
        return null;
    }

    /**
     * 添加Activity到堆栈
     */
    public static void push(Activity activity) {
        activityStack.push(activity);
    }

    /**
     * 从堆栈移除activity
     */
    public static void remove(Activity activity) {
        if (activity != null && activityStack.contains(activity)) {
            activityStack.remove(activity);
        }
    }

    /**
     * 获取当前Activity(堆栈中最后一个压入的)
     */
    public static Activity lastActivity() {
        if (activityStack.isEmpty()) {
            return null;
        }
        return activityStack.lastElement();
    }

    /**
     * 获取first Activity(堆栈中第一个压入的)
     */
    public static Activity firstActivity() {
        if (activityStack.isEmpty()) {
            return null;
        }
        return activityStack.firstElement();
    }

    public static boolean activityStackIsEmpty() {
        return activityStack.isEmpty();
    }

    public static boolean activityStackIsNotEmpty() {
        return !activityStack.isEmpty();
    }

    /**
     * 结束指定的Activity
     */
    public static void finishAndRemoveActivity(Activity activity) {
        if (activity != null && activityStack.contains(activity)) {
            activityStack.remove(activity);
            activity.finish();
        }
    }

    public static void finishActivity(Activity activity) {
        if (activity != null) {
            activity.finish();
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class cls) {
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishAndRemoveActivity(activity);
                break;
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity() {
        Activity topActivity;
        while ((topActivity = activityStack.pop()) != null) {
            finishActivity(topActivity);
        }
    }

    /**
     * 退出应用程序
     */
    public static void appExit() {
        try {
            finishAllActivity();
            // 杀死该应用进程
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(activity堆栈式管理)