繼承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並finish19 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 }