Android Activity栈管理 制定关闭某一个Activity,关闭所有Activit
程序员文章站
2022-05-03 13:33:57
api :打开新的activity 关闭之前所有activity。
intent intent = new intent(this, loginactivity.class);
intent....
api :打开新的activity 关闭之前所有activity。
intent intent = new intent(this, loginactivity.class); intent.setflags(intent.flag_activity_clear_task | intent.flag_activity_new_task); startactivity(intent);
自己管理: 将activity放入集合进行管理
/** * activity管理类 * */ public class appmanager { private static stack activitystack; private static appmanager instance; private appmanager() { } /** * 单一实例 */ public static appmanager getappmanager() { if (instance == null) { instance = new appmanager(); } return instance; } /** * 添加activity到堆栈 */ public void addactivity(activity activity) { if (activitystack == null) { activitystack = new stack(); } activitystack.add(activity); } /** * 获取当前activity(堆栈中最后一个压入的) */ public activity currentactivity() { activity activity = activitystack.lastelement(); return activity; } /** * 结束当前activity(堆栈中最后一个压入的) */ public void finishactivity() { activity activity = activitystack.lastelement(); finishactivity(activity); } /** * 结束指定的activity */ public void finishactivity(activity activity) { if (activity != null) { activitystack.remove(activity); activity.finish(); activity = null; } } /** * 结束指定类名的activity */ public void finishactivity(class cls) { for (activity activity : activitystack) { if (activity.getclass().equals(cls)) { finishactivity(activity); } } } /** * 结束所有activity */ public void finishallactivity() { for (int i = 0, size = activitystack.size(); i < size; i++) { if (null != activitystack.get(i)) { activitystack.get(i).finish(); } } activitystack.clear(); } /** * 退出应用程序 */ @suppresswarnings("deprecation") public void appexit(context context) { try { finishallactivity(); activitymanager activitymanager = (activitymanager) context.getsystemservice(context.activity_service); activitymanager.restartpackage(context.getpackagename()); system.exit(0); } catch (exception e) { e.printstacktrace(); } } }