在网上找了好几个完美退出app的方法,都看了一下,最后选择了一个靠谱的ExitApplication来继承Application来退出应用,但是其中也遇到很多问题。
先贴一段网上都有的代码:ExitApplication.java
package com.biceng.utils; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.Application; public class ExitApplication extends Application { private static ExitApplication exitApplication; private List<Activity> activityList = new LinkedList<Activity>(); private ExitApplication() { super(); } public static ExitApplication getInstance() { if (exitApplication == null) { return new ExitApplication(); } else { return exitApplication; } } public void addActivity(Activity activity) { activityList.add(activity); } public void exit() { for (Activity activity : activityList) { activity.finish(); } System.exit(0); } }
再每个activity的oncreate()方法里都加上一句:ExitApplication.getInstance().addActivity(this);
在想退出时,退出方法里调用:ExitApplication.getInstance().exit();
这样一看,这个方法其实一点问题都没有,但是,在实测中,总是出现退出不了的问题。
问题困扰了我不少时间,也在网上找了很多类似的代码,修修改改,均没有效果。
最后无意间,看到了一个大神的blog中,也有一段类似的代码,细心研究了一番,他的代码更严谨,增加了线程同步的概念,提醒系统回收垃圾等。
大神的代码:
package com.biceng.utils; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.Application; public class ExitApplication extends Application { private static ExitApplication instance; private List<Activity> activityList = new LinkedList<Activity>(); private ExitApplication() { } public synchronized static ExitApplication getInstance() { if (null == instance) { instance = new ExitApplication(); } return instance; } public void addActivity(Activity activity) { activityList.add(activity); } public void exit() { try { for (Activity activity : activityList) { if (activity != null) activity.finish(); } } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } } @Override public void onLowMemory() { super.onLowMemory(); System.gc(); //告诉系统回收 } }
附上大神的blog地址:
http://blog.csdn.net/way_ping_li