上网学了好多方法,关于Android的Activity如何退出。好多方法都不行啦,试了各种方法,下面这种方法就是我最喜欢的,简单又容易懂。
使用单例模式创建一个Activity管理对象,该对象中有一个Activity容器(具体实现自己处理,使用LinkedList等)专门负责存储新开启的每一个Activity,并且容易理解、易于操作,非常不错!
MyApplication类(储存每一个Activity,并实现关闭所有Activity的操作
- public class MyApplication extends Application {
- private List<Activity> activityList = new LinkedList<Activity>();
- private static MyApplication instance;
- private MyApplication()
- {
- }
- //单例模式中获取唯一的MyApplication实例
- public static MyApplication getInstance()
- {
- if(null == instance)
- {
- instance = new MyApplication();
- }
- return instance;
- }
- //添加Activity到容器中
- public void addActivity(Activity activity)
- {
- activityList.add(activity);
- }
- //遍历所有Activity并finish
- public void exit()
- {
- for(Activity activity:activityList)
- {
- activity.finish();
- }
- System.exit(0);
- }
- }
public class MyApplication extends Application { private List<Activity> activityList = new LinkedList<Activity>(); private static MyApplication instance; private MyApplication() { } //单例模式中获取唯一的MyApplication实例 public static MyApplication getInstance() { if(null == instance) { instance = new MyApplication(); } return instance; } //添加Activity到容器中 public void addActivity(Activity activity) { activityList.add(activity); } //遍历所有Activity并finish public void exit() { for(Activity activity:activityList) { activity.finish(); } System.exit(0); } }
在每一个Activity中的onCreate方法里添加该Activity到MyApplication对象实例容器中
- MyApplication.getInstance().addActivity(this);
MyApplication.getInstance().addActivity(this);
在需要结束所有Activity的时候调用exit方法
- MyApplication.getInstance().exit();