为了安全退出多个已创建的activity?
可以自定义application:myapplication.
增加一个list成员保存,一些关键的已创建的activity实例:
1 private ListactivityList = new LinkedList (); 2 3 // 保存 所有activity的this 4 public void addActivity(Activity activity) { 5 activityList.add(activity); 6 } 7 8 public void exit() { 9 // save cache data to db10 CacheManager cacheManager = CacheManager.getInstance(this);11 cacheManager.saveNewCache1ToDB();12 this.msgNewListMap.clear();13 for (Activity activity : activityList) {14 activity.finish();15 }16 }
然后在activit创建的时候,oncreate中添加该activity到list中
1 MyApplication.getInstance().addActivity(ChatListActivity.this);
在程序退出时,例如双击返回键退出程序,调用application的exit方法:
1 // 退出 2 @Override 3 public boolean onKeyDown(int keyCode, KeyEvent event) { 4 // TODO Auto-generated method stub 5 if (keyCode == KeyEvent.KEYCODE_BACK) { 6 long currentTime = System.currentTimeMillis(); 7 if ((currentTime - touchTime) >= waitTime) { 8 showCustomToast(R.string.main_exit); 9 touchTime = currentTime;10 } else {11 // android.os.Process.killProcess(android.os.Process.myPid());12 MyApplication.getInstance().exit();13 }14 return true;15 16 }17 return super.onKeyDown(keyCode, event);18 }
代码完整路径:http://git.oschina.net/zj2012zy/Android-Demo/tree/master/CustomApplication