Android技术揭秘之activity堆栈管理
Posted 王永迪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android技术揭秘之activity堆栈管理相关的知识,希望对你有一定的参考价值。
定义activity基类
public class BaseActivity extends Activity
/** activity 入栈 */
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
ActivitiesManager.getInstance().pushActivity(this);
/** activity 出栈 */
@Override
protected void onDestroy()
super.onDestroy();
ActivitiesManager.getInstance().popActivity();
activity堆栈管理器
public class ActivitiesManager
private static final String TAG = "ActivitiesManager";
private Stack<Activity> mActivityStack = new Stack<Activity>()
static class SingletonHolder
static ActivitiesManager instance = new ActivitiesManager();
public static ActivitiesManager getInstance()
return SingletonHolder.instance;
private EventDispatcher()
public int stackSize()
return mActivityStack.size();
public Activity getCurrentActivity()
Activity activity = null;
try
activity = mActivityStack.lastElement();
catch (Exception e)
return null;
return activity;
public void popActivity()
Activity activity = mActivityStack.lastElement();
if (null != activity)
activity.finish();
mActivityStack.remove(activity);
activity = null;
public void popActivity(Activity activity)
if (null != activity)
mActivityStack.remove(activity);
activity = null;
public void pushActivity(Activity activity)
mActivityStack.add(activity);
public void popAllActivities()
while (!mActivityStack.isEmpty())
Activity activity = getCurrentActivity();
if (null == activity)
break;
activity.finish();
popActivity(activity);
public void popSpecialActivity(Class<?> cls)
try
Iterator<Activity> iterator = mActivityStack.iterator();
Activity activity = null;
while (iterator.hasNext())
activity = iterator.next();
if (activity.getClass().equals(cls))
activity.finish();
iterator.remove();
activity = null;
catch (Exception e)
/** 查看当前的所有活动 */
public void peekActivity()
for (Activity activity : mActivityStack)
if (null == activity)
break;
以上是关于Android技术揭秘之activity堆栈管理的主要内容,如果未能解决你的问题,请参考以下文章