一招搞定Android Activity的管理

weixin_34293059發表於2017-03-13

為什麼要做activity的管理


在android app的開發過程中,或多或少會涉及到activity的管理。會有這樣的業務場景存在,例如:

  • 廣播接收器接收到某個動作,需要finish某個指定的activity;
  • 在缺乏activity上下文的地方也需要finish某個指定的activity......

話不多說,上程式碼。

1. AppManager.java

/**
 * ProjectName:AndroidUtil
 * PackageName: com.standard.util.helper
 * Description:自定義activity的棧管理(棧結構擴充套件Vector,元素不要求唯一性,可存在多個相同例項)
 * <p>
 * CreateTime: 6/24/2016 12:36
 * Modifier:liminghuang
 * ModifyTime:6/24/2016 12:36
 * Comment:因為第一版本AppManager的使用過程中發現存在問題,所以為了保持api的一致性,採用橋接模式委託AppManagerDelegate類處理
 *
 * @author liminghuang
 */
public final class AppManager {
    /** 是否使用橋接模式 **/
    private boolean isBridge = false;
    /** AppManager管理activity的委託類 **/
    private AppManagerDelegate mDelegate;
    /** 維護activity的棧結構 **/
    private Stack<Activity> mActivityStack;
    private static volatile AppManager sInstance;
    /**
     * 隱藏構造器
     *
     * @param isBridge 是否開啟橋接模式
     */
    private AppManager(boolean isBridge) {
        this.isBridge = isBridge;
        mDelegate = AppManagerDelegate.getInstance();
    }
    /**
     * 單例
     *
     * @return 返回AppManager的單例
     */
    public static AppManager getInstance() {
        if (sInstance == null) {
            synchronized (AppManager.class) {
                if (sInstance == null) {
                    sInstance = new AppManager(true);
                }
            }
        }
        return sInstance;
    }
    /**
     * 新增Activity到堆疊
     *
     * @param activity activity例項
     */
    public void addActivity(Activity activity) {
        if (isBridge) {
            mDelegate.addActivity(activity);
        } else {
            if (mActivityStack == null) {
                mActivityStack = new Stack<>();
            }
            mActivityStack.add(activity);
        }
    }
    /**
     * 獲取當前Activity(棧中最後一個壓入的)
     *
     * @return 當前(棧頂)activity
     */
    public Activity currentActivity() {
        if (isBridge) {
            return mDelegate.currentActivity();
        } else {
            if (mActivityStack != null && !mActivityStack.isEmpty()) {
                return mActivityStack.lastElement();
            }
            return null;
        }
    }
    /**
     * 結束除當前activtiy以外的所有activity
     * 注意:不能使用foreach遍歷併發刪除,會丟擲java.util.ConcurrentModificationException的異常
     *
     * @param activity 不需要結束的activity
     */
    public void finishOtherActivity(Activity activity) {
        if (isBridge) {
            mDelegate.finishOtherActivity(activity);
        } else {
            if (mActivityStack != null) {
                for (Iterator<Activity> it = mActivityStack.iterator(); it.hasNext(); ) {
                    Activity temp = it.next();
                    if (temp != null && temp != activity) {
                        finishActivity(temp);
                    }
                }
            }
        }
    }
    /**
     * 結束除這一類activtiy以外的所有activity
     * 注意:不能使用foreach遍歷併發刪除,會丟擲java.util.ConcurrentModificationException的異常
     *
     * @param cls 不需要結束的activity
     */
    public void finishOtherActivity(Class<?> cls) {
        if (isBridge) {
            mDelegate.finishOtherActivity(cls);
        } else {
            if (mActivityStack != null) {
                for (Iterator<Activity> it = mActivityStack.iterator(); it.hasNext(); ) {
                    Activity activity = it.next();
                    if (!activity.getClass().equals(cls)) {
                        finishActivity(activity);
                    }
                }
            }
        }
    }
    /**
     * 結束當前Activity(堆疊中最後一個壓入的)
     */
    public void finishActivity() {
        if (isBridge) {
            mDelegate.finishActivity();
        } else {
            if (mActivityStack != null && !mActivityStack.isEmpty()) {
                Activity activity = mActivityStack.lastElement();
                finishActivity(activity);
            }
        }
    }
    /**
     * 結束指定的Activity
     *
     * @param activity 指定的activity例項
     */
    public void finishActivity(Activity activity) {
        if (isBridge) {
            mDelegate.finishActivity(activity);
        } else {
            if (activity != null) {
                if (mActivityStack != null && mActivityStack.contains(activity)) {// 相容未使用AppManager管理的例項
                    mActivityStack.remove(activity);
                }
                activity.finish();
            }
        }
    }
    /**
     * 結束指定類名的所有Activity
     *
     * @param cls 指定的類的class
     */
    public void finishActivity(Class<?> cls) {
        if (isBridge) {
            mDelegate.finishActivity(cls);
        } else {
            if (mActivityStack != null) {
                for (Iterator<Activity> it = mActivityStack.iterator(); it.hasNext(); ) {
                    Activity activity = it.next();
                    if (activity.getClass().equals(cls)) {
                        finishActivity(activity);
                    }
                }
            }
        }
    }
    /**
     * 結束所有Activity
     */
    public void finishAllActivity() {
        if (isBridge) {
            mDelegate.finishAllActivity();
        } else {
            if (mActivityStack != null) {
                for (int i = 0, size = mActivityStack.size(); i < size; i++) {
                    if (null != mActivityStack.get(i)) {
                        mActivityStack.get(i).finish();
                    }
                }
                mActivityStack.clear();
            }
        }
    }
    /**
     * 退出應用程式
     */
    public void exitApp() {
        if (isBridge) {
            mDelegate.exitApp();
        } else {
            try {
                finishAllActivity();
                // 退出JVM(java虛擬機器),釋放所佔記憶體資源,0表示正常退出(非0的都為異常退出)
                System.exit(0);
                // 從作業系統中結束掉當前程式的程式
                android.os.Process.killProcess(android.os.Process.myPid());
            } catch (Exception e) {
                LogUtil.e("Exit exception", e);
            }
        }
    }
}

2. AppManagerDelegate.java

/**
 * ProjectName:AndroidUtil
 * PackageName: com.standard.util.helper
 * Description:自定義activity的棧管理(棧結構擴充套件Vector,元素不要求唯一性,可存在多個相同例項)
 * <p>
 * CreateTime: 6/24/2016 12:36
 * Modifier:liminghuang
 * ModifyTime:6/24/2016 12:36
 * Comment:
 *
 * @author liminghuang
 */
public final class AppManagerDelegate {
    
    // 使用弱引用是因為存在未使用AppManager的finish方法來釋放的activity,但mActivityStack並未斷開對其應用導致記憶體洩露的問題
    private Stack<WeakReference<Activity>> mActivityStack;
    private static volatile AppManagerDelegate sInstance;
    
    private AppManagerDelegate() {
    }
    
    /**
     * 單例
     *
     * @return 返回AppManager的單例
     */
    public static AppManagerDelegate getInstance() {
        if (sInstance == null) {
            synchronized (AppManagerDelegate.class) {
                if (sInstance == null) {
                    sInstance = new AppManagerDelegate();
                }
            }
        }
        return sInstance;
    }
    
    /**
     * 新增Activity到堆疊
     *
     * @param activity activity例項
     */
    public void addActivity(Activity activity) {
        if (mActivityStack == null) {
            mActivityStack = new Stack<>();
        }
        mActivityStack.add(new WeakReference<>(activity));
    }
    /**
     * 檢查弱引用是否釋放,若釋放,則從棧中清理掉該元素
     */
    public void checkWeakReference() {
        if (mActivityStack != null) {
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                if (temp == null) {
                    it.remove();// 使用迭代器來進行安全的加鎖操作
                }
            }
        }
    }
    
    /**
     * 獲取當前Activity(棧中最後一個壓入的)
     *
     * @return 當前(棧頂)activity
     */
    public Activity currentActivity() {
        checkWeakReference();
        if (mActivityStack != null && !mActivityStack.isEmpty()) {
            return mActivityStack.lastElement().get();
        }
        return null;
    }
    
    /**
     * 結束除當前activtiy以外的所有activity
     * 注意:不能使用foreach遍歷併發刪除,會丟擲java.util.ConcurrentModificationException的異常
     *
     * @param activtiy 不需要結束的activity
     */
    public void finishOtherActivity(Activity activtiy) {
        if (mActivityStack != null && activtiy != null) {
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                if (temp == null) {// 清理掉已經釋放的activity
                    it.remove();
                    continue;
                }
                if (temp != activtiy) {
                    it.remove();// 使用迭代器來進行安全的加鎖操作
                    temp.finish();
                }
            }
        }
    }
    /**
     * 結束除這一類activtiy以外的所有activity
     *
     * @param cls 指定的某類activity
     */
    public void finishOtherActivity(Class<?> cls) {
        if (mActivityStack != null) {
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity activity = activityReference.get();
                if (activity == null) {// 清理掉已經釋放的activity
                    it.remove();
                    continue;
                }
                if (!activity.getClass().equals(cls)) {
                    it.remove();// 使用迭代器來進行安全的加鎖操作
                    activity.finish();
                }
            }
        }
    }
    
    /**
     * 結束當前Activity(堆疊中最後一個壓入的)
     */
    public void finishActivity() {
        Activity activity = currentActivity();
        if (activity != null) {
            finishActivity(activity);
        }
    }
    
    /**
     * 結束指定的Activity
     *
     * @param activity 指定的activity例項
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                if (temp == null) {// 清理掉已經釋放的activity
                    it.remove();
                    continue;
                }
                if (temp == activity) {
                    it.remove();
                }
            }
            activity.finish();
        }
    }
    
    /**
     * 結束指定類名的所有Activity
     *
     * @param cls 指定的類的class
     */
    public void finishActivity(Class<?> cls) {
        if (mActivityStack != null) {
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity activity = activityReference.get();
                if (activity == null) {// 清理掉已經釋放的activity
                    it.remove();
                    continue;
                }
                if (activity.getClass().equals(cls)) {
                    it.remove();
                    activity.finish();
                }
            }
        }
    }
    
    /**
     * 結束所有Activity
     */
    public void finishAllActivity() {
        if (mActivityStack != null) {
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity activity = activityReference.get();
                if (activity != null) {
                    activity.finish();
                }
            }
            mActivityStack.clear();
        }
    }
    
    /**
     * 退出應用程式
     */
    public void exitApp() {
        try {
            finishAllActivity();
            // 退出JVM(java虛擬機器),釋放所佔記憶體資源,0表示正常退出(非0的都為異常退出)
            System.exit(0);
            // 從作業系統中結束掉當前程式的程式
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (Exception e) {
            LogUtil.e("Exit exception", e);
        }
    }
}

如何使用

  • 在BaseActivity#onCreate回撥中新增AppManager.getInstance().addActivity(this)
  • 獲取當前棧頂activityAppManager.getInstance().currentActivity()
  • 在需要銷燬的當前activity的地方呼叫AppManager.getInstance().finishActivity()
  • 在需要銷燬指定類別例項的地方呼叫AppManager.getInstance().finishActivity(XXX.class)
  • 在需要銷燬指定類別除外的其他例項的地方呼叫AppManager.getInstance().finishOtherActivity(XXX.class)
  • 退出應用呼叫AppManager.getInstance().exitApp()

下一篇:記一次Handler的優化

相關文章