public class ActivityManager {
//增加删除操作多,栈是先进后出
public Stack<Activity> mActivities;
private ActivityManager() {
mActivities = new Stack<>();
}
//双重校验锁
private static volatile ActivityManager mInstance;
public static ActivityManager getInstance() {
if (mInstance == null) {
synchronized (ActivityManager.class) {
if (mInstance == null) {
mInstance = new ActivityManager();
}
}
}
return mInstance;
}
/**
* 添加
*/
public void attach(Activity activity) {
if (activity != null) {
mActivities.add(activity);
}
}
/**
* 移除解绑 - 防止内存泄漏
*/
public void detach(Activity activity) {
int size = mActivities.size();
for (int i = size - 1; i >= 0; i--) {
Activity currentActivity = mActivities.get(i);
if (currentActivity.getClass().equals(activity.getClass())) {
mActivities.remove(i);
size--;
i++;
}
}
}
/**
* 移除指定的activity
* 先进后出
*/
public void remove(Activity activity) {
int size = mActivities.size();
for (int i = size - 1; i > 0; i--) {
Activity currentActivity = mActivities.get(i);
if (currentActivity.getClass().equals(activity.getClass())) {
//销毁当前activity
currentActivity.finish();
mActivities.remove(i);//从栈空间移除
i++;
size--;
}
}
}
/**
* 根据当前的类名进行关闭
*/
public void finish(Class<? extends Activity> activityClass){
int size = mActivities.size();
for (int i = size-1; i > 0; i--) {
Activity activity = mActivities.get(i);
if(activity.getClass().getCanonicalName().equals(activityClass.getCanonicalName())){
activity.finish();
mActivities.remove(i);
i++;
size--;
}
}
}
/**
* 删除当前的activity
*/
public void removeCurrent() {
/* Activity activity = mActivities.get(mActivities.size() - 1);
activity.finish();
mActivities.remove(mActivities.size()-1);*/
Activity activity = mActivities.lastElement();
activity.finish();
mActivities.remove(activity);
}
/**
* 移除所有的activity
*/
public void removeAll() {
for (int i = mActivities.size() - 1; i >= 0; i--) {
Activity activity = mActivities.get(i);
activity.finish();
mActivities.remove(activity);
}
}
//返回栈大小
public int size() {
return mActivities.size();
}
}
单例模式之强大的activity的管理
最新推荐文章于 2024-09-29 20:18:52 发布