1. 程式人生 > >安卓中管理Activity

安卓中管理Activity

安卓中一般在BaseActivity 管理所有的Activity 因為所有的Activity 繼承自BaseActivity

步驟:

1:在BaseActivity New 一個ArrayList 儲存Activity

private  List<Activity> allActivity = new ArrayList<>();

2.寫兩個方法進行新增Activity到allActivity中

protected void registerActivity(Activity activity) {
    allActivity.add(activity);
}

protected void unRegisterActivity(final Activity activity) {
    if (getCurrentActivity() == activity) {
        setCurrentActivity(null);
    }
    allActivity.remove(activity);
}

3.在BaseActivity的OnCreate()方法中:

registerActivity(this);

4.在BaseActivity的OnDestory()方法中:

unRegisterActivity(this);

5.如果某個Activity不想加入allActivity 進行管理  就重寫上面兩個方法

@Override
protected void registerActivity(Activity activity) {
  //去掉super()
}

@Override
protected void unRegisterActivity(Activity activity) {
//去掉super()
}

6.如果要銷燬所有的Activity

在BaseActivity中新增一個方法:

public static void finishAllActivity() {
    if (!ThreadExecutor.isMainThread()) {
        throw new IllegalStateException("Must called on main thread");
    }
    for (Activity activity : allActivity) {
        if (activity != null) {
            activity.finish();
        }
    }
    allActivity.clear();
}

在想呼叫的地方呼叫即可

個人GitHub:  https://github.com/HuaDanJson