今天在网上看见个博客关于退出整个程序的,感觉不错,拿来分享学习

SysApplication这个类复制到工程里面,然后在每个Acitivity的oncreate方法里面通过SysApplication.getInstance().addActivity(this); 添加当前Acitivity到ancivitylist里面去,*后在想退出的时候调用SysApplication.getInstance().exit();可直接关闭所有的Acitivity并退出应用程序。

  1. import java.util.LinkedList;
  2. import java.util.List;
  3. import android.app.Activity;
  4. import android.app.AlertDialog;
  5. import android.app.Application;
  6. import android.content.DialogInterface;
  7. import android.content.Intent;
  8. public class SysApplication extends Application {
  9. private List mList = new LinkedList();
  10. private static SysApplication instance;
  11. private SysApplication() {
  12. }
  13. public synchronized static SysApplication getInstance() {
  14. if (null == instance) {
  15. instance = new SysApplication();
  16. }
  17. return instance;
  18. }
  19. // add Activity
  20. public void addActivity(Activity activity) {
  21. mList.add(activity);
  22. }
  23. public void exit() {
  24. try {
  25. for (Activity activity : mList) {
  26. if (activity != null)
  27. activity.finish();
  28. }
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. } finally {
  32. System.exit(0);
  33. }
  34. }
  35. public void onLowMemory() {
  36. super.onLowMemory();
  37. System.gc();
  38. }
  39. }

在应用程序里面 的activity的oncreate里面添加SysApplication.getInstance().addActivity(this)
如:

  1. public void onCreate(Bundle savedInstanceState)
  2. {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.main);
  5. SysApplication.getInstance().addActivity(this);
  6. }