Android完全退出的方案

继承Application,实现一个Activity的管理器容器,管理所有的Activity,在用户明确退出应用的时候,循环遍历所有的Activity,并调用其finish()。

伪代码如下:

 1 public class MyApplication extends Application {
 2 
 3         private List<Activity> activityList = new LinkedList<Activity>();
 4         private static MyApplication instance;
 5         private MyApplication() {}
 6         public static MyApplication getInstance() {
 7                 if ( instance == null ) {
 8                         instance = new MyApplication();
 9                 }
10                 return instance;
11         }
12 
13         // 添加Activity到容器中
14         public void addActivity(Activity activity) {
15                 activityList.add(activity);
16         }
17 
18         // 遍历所有Activity并finish
19         public void exit() {
20                 for (Activity activity : activityList) {
21                         activity.finish();
22                 }
23                 System.exit(0);
24         }
25 }

 

Activity Manager :

 1 public class ScreenManager {
 2 
 3     private static Stack<Activity> activityStack;
 4     private static ScreenManager instance;
 5 
 6     public static ScreenManager getScreenManager() {
 7         if (instance == null) {
 8             instance = new ScreenManager();
 9         }
10         return instance;
11     }
12     public Activity lastActivity() {
13         Activity activity = activityStack.lastElement();
14         return activity;
15     }
16     public void popActivity(Activity activity) {
17         if (activity != null) {
18             activityStack.remove(activity);
19             activity = null;
20         }
21     }
22     
23     public int activityCount() {
24         return activityStack.size();
25     }
26     
27     public void pushActivity(Activity activity) {
28         if (activityStack == null) {
29             activityStack = new Stack<Activity>();
30         }
31         activityStack.add(activity);
32     }
33 
34     public void popAllActivityExceptOne(Class cls) {
35         while (true) {
36             Activity activity = lastActivity();
37             if (activity == null) {
38                 break;
39             }
40             if (activity.getClass().equals(cls)) {
41                 break;
42             }
43             popActivity(activity);
44         }
45     }
46 }
posted @ 2013-03-14 09:36  芈希有  阅读(242)  评论(0编辑  收藏  举报