安卓开发一般都需要进行Activity的管理,常用操作老司机已为你封装完毕,经常有小伙伴问怎么进行管理,那我告诉你,你可以用这份工具进行管理,具体可以查看源码,现在为你开车,Demo传送门。
站点
管理和回收Activity → AppDavikActivityMgr
getScreenManager : 单例堆栈集合对象
removeActivity : 堆栈中销毁并移除
removeAllActivity : 栈中销毁并移除所有Act对象
currentActivity : 取当前Act对象
getCurrentActivityName: 获得当前Act的类名
addActivity : 将Act纳入推栈集合中
exitApp : 退出栈中所有Activity
具体路线
public class AppDavikActivityMgr {
//存储ActivityStack
private static Stack<Activity> activityStack = new Stack<Activity>();
//单例模式
private static AppDavikActivityMgr instance;
/**
* 单列堆栈集合对象
* @return AppDavikActivityMgr 单利堆栈集合对象
*/
public static AppDavikActivityMgr getScreenManager() {
if (instance == null) {
synchronized (AppDavikActivityMgr.class){
if (instance == null) {
instance = new AppDavikActivityMgr();
}
}
}
return instance;
}
/**
* 堆栈中销毁并移除
* @param activity 指定Act对象
*/
public void removeActivity(Activity activity) {
AppLogMessageMgr.i("AppDavikActivityMgr-->>removeActivity", activity != null ? activity.toString() : "");
if (null != activity) {
activityStack.remove(activity);
activity.finish();
activity = null;
}
}
/**
* 栈中销毁并移除所有Act对象
*/
public void removeAllActivity() {
if (null != activityStack && activityStack.size() > 0) {
//创建临时集合对象
Stack<Activity> activityTemp = new Stack<Activity>();
for (Activity activity : activityStack) {
if (null != activity) {
//添加到临时集合中
activityTemp.add(activity);
//结束Activity
activity.finish();
}
}
activityStack.removeAll(activityTemp);
}
AppLogMessageMgr.i("AppDavikActivityMgr-->>removeAllActivity", "removeAllActivity");
System.gc();
System.exit(0);
}
/**
* 获取当前Act对象
* @return Activity 当前act
*/
public Activity currentActivity() {
Activity activity = null;
if (!activityStack.empty()){
activity = activityStack.lastElement();
}
AppLogMessageMgr.i("AppDavikActivityMgr-->>currentActivity", activity + "");
return activity;
}
/**
* 获得当前Act的类名
* @return String
*/
public String getCurrentActivityName() {
String actSimpleName = "";
if (!activityStack.empty()) {
actSimpleName = activityStack.lastElement().getClass().getSimpleName();
}
AppLogMessageMgr.i("AppDavikActivityMgr-->>getCurrentActivityName", actSimpleName);
return actSimpleName;
}
/**
* 将Act纳入推栈集合中
* @param activity Act对象
*/
public void addActivity(Activity activity) {
AppLogMessageMgr.i("AppDavikActivityMgr-->>addActivity", activity != null ? activity.toString() : "");
if (null == activityStack) {
activityStack = new Stack<Activity>();
}
activityStack.add(activity);
}
/**
* 退出栈中所有Activity
* @param cls
* @return void
*/
public void exitApp(Class<?> cls) {
AppLogMessageMgr.i("AppDavikActivityMgr-->>exitApp", "exitApp-->>占用内存:" + Runtime.getRuntime().totalMemory());
while (true) {
Activity activity = currentActivity();
if (null == activity) {
break;
}
if (activity.getClass().equals(cls)) {
break;
}
removeActivity(activity);
}
System.gc();
System.exit(0);
}
}
终点站
好了,终点站到了,如果对本次旅途满意的话,请给五星好评哦,没关注的小伙伴轻轻点个上方的关注,毕竟老司机牺牲了很多时间才换来这么一份工具类,如果该工具类依赖其他工具类,都可以在我的史上最全的常用开发工具类收集(持续更新中)中找到。