标签:android activity管理 内存管理 管理类 程序员
项目开启的Activity越多,占的内存越多,我们是不是有时候想当我打开很多界面的时候,我们到底打开多少个Activity,OK现在你的难题解决了,只有把这个Activity管理类复制到你的项目当中,随时随地管理的你的Activity,让你成为内存的主导者!不要问我叫什么,请叫我雷锋!首先看看效果图:
代码献上:
/** * 2014-6-7 上午10:40:16 */ package com.jiub.client.mobile.manager; import java.util.Stack; import android.app.Activity; import com.jiub.client.mobile.utils.QLog; /** * @author zqy * * */ public class ScreenManager { private final static String TAG=ScreenManager.class.getSimpleName(); private static Stack<Activity> activityStack; private static ScreenManager instance; public static ScreenManager getScreenManager(){ if (instance == null) { instance = new ScreenManager(); } QLog.i(TAG, "ScreenManager create"); return instance; } /** * 从栈中移除最后一个元?? */ public void popActivity(){ Activity activity = currentActivity(); if (activity != null) { if (!activity.isFinishing()) { activity.finish(); } activityStack.removeElement(activity); activity = null; } QLog.i(TAG, "ScreenManager popActivity "); } /** * 从栈中移除指定的元素 * @param activity */ public void popActivity(Activity activity){ if (activity != null) { QLog.i(TAG, "要删除"+activity.getClass().getSimpleName()); if (!activity.isFinishing()) { activity.finish(); QLog.i(TAG, activity.getClass().getSimpleName()+"正在关闭"); }else{ QLog.i(TAG, activity.getClass().getSimpleName()+"已经关闭"); } activityStack.removeElement(activity); QLog.i(TAG, activity.getClass().getSimpleName()+"从栈中移除"); activity = null; } int size=activityStack.size(); QLog.i(TAG, "删除后个数"+size); } /** * 将新元素添加到栈中 * @param activity */ public void pushActivity(Activity activity){ if (activityStack == null) { activityStack = new Stack<Activity>(); } activityStack.addElement(activity); QLog.i(TAG, "加入"+activity.getClass().getSimpleName()); int size=activityStack.size(); QLog.i(TAG, "添加后个数"+size); } /** * 获取栈顶元素 * @return */ public Activity currentActivity(){ Activity activity = null; try { activity = activityStack.lastElement(); } catch (Exception e) { } return activity; } /** * 移除全部元素,除了指定类型的以外 * @param cls */ public void popAllActivityExceptOne(Class<?> cls){ int size = activityStack.size(); for (int i = 0; i < size; i++) { Activity activity = activityStack.get(i); if (activity != null && activity.getClass().equals(cls)) { }else{ popActivity(activity); size--; i--; } } } /** * 按照给定的Class,结束一个Activity * @param cls */ public void finishActivityByClass(Class<?> cls){ int size = activityStack.size(); for (int i = 0; i < size; i++) { Activity activity = activityStack.get(i); if (activity != null && activity.getClass().equals(cls)) { popActivity(activity); size--; i--; } } } }
protected ScreenManager mScreenManager;//初始化
mScreenManager = ScreenManager.getScreenManager(); mScreenManager.pushActivity(this);在Activity的onDestroy方法里面写上这行代码
mScreenManager.popActivity(this);但是那如果你有BaseActivity就不需要在每个Activity里面写了,把上面的四行代码写在BaseActivity里面就行了
标签:android activity管理 内存管理 管理类 程序员
原文地址:http://blog.csdn.net/xiaoyuan511/article/details/39320097