Activity管理
2019-04-18 本文已影响0人
桃花江里小龙虾
创建BaseAppManager
/**
* Create By Chen en on 2019/4/18
* Class Note:
* use {@link LinkedList} to manage your activity stack
*/
public class BaseAppManager {
private static BaseAppManager instance = null;
private static List<Activity> mActivities = new LinkedList<Activity>();
private BaseAppManager() {
}
public static BaseAppManager getInstance() {
if (null == instance) {
synchronized (BaseAppManager.class) {
if (null == instance) {
instance = new BaseAppManager();
}
}
}
return instance;
}
//获取activity个数
public int size() {
return mActivities.size();
}
//获取前一个activity
public synchronized Activity getForwardActivity() {
return size() > 0 ? mActivities.get(size() - 1) : null;
}
//添加activity
public synchronized void addActivity(Activity activity) {
mActivities.add(activity);
}
//结束activity
public synchronized void removeActivity(Activity activity) {
if (mActivities.contains(activity)) {
mActivities.remove(activity);
}
}
//结束所以activity
public synchronized void clear() {
for (int i = mActivities.size() - 1; i > -1; i--) {
Activity activity = mActivities.get(i);
removeActivity(activity);
activity.finish();
i = mActivities.size();
}
}
//保留后两位activity
public synchronized void clearTop() {
for (int i = mActivities.size() - 2; i > -1; i--) {
Activity activity = mActivities.get(i);
removeActivity(activity);
activity.finish();
i = mActivities.size() - 1;
}
}
//保留当前activity
public synchronized void clearToLiveTopAndBottom() {
for (int i = mActivities.size() - 1; i > 0; i--) {
Activity activity = mActivities.get(i);
removeActivity(activity);
activity.finish();
}
}
//结束当前和上一个activity
public synchronized void clearTopTow() {
LoggerUtil.e("BaseAppManager", " clearTopTow : i " + (mActivities.size() - 1) + " index : " + (mActivities.size() - 2));
int index = mActivities.size() - 3;
for (int i = mActivities.size() - 1; i > index; i--) {
Activity activity = mActivities.get(i);
removeActivity(activity);
activity.finish();
}
}
使用:为了进行统一处理,我们可以写在BaseActivity中:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BaseAppManager.getInstance().addActivity(this); //添加
}
@Override
public void finish() {
super.finish();
BaseAppManager.getInstance().removeActivity(this);//移除
}