android 完美退出所有Activity的demo
项目地址:https://github.com/libill/myapplication
利用android的wheel和参考android完美退出程序做出来的demo,结束掉所有打开的Activity,并把记录打开的Activity用log打印出来。
1、myapplication继承application
1 package kankan.wheel.demo; 2 3 import java.util.LinkedList; 4 import java.util.List; 5 6 import android.app.Activity; 7 import android.app.Application; 8 import android.util.Log; 9 10 public class MyApplication extends Application { 11 12 private static List<Activity> activityList = new LinkedList<Activity>(); 13 private static MyApplication instance; 14 15 public MyApplication() { 16 } 17 18 // 单例模式中获取唯一的MyApplication实例 19 public static MyApplication getInstance() { 20 if (null == instance) { 21 instance = new MyApplication(); 22 } 23 return instance; 24 } 25 26 // 添加Activity到容器中 27 public void addActivity(Activity activity) { 28 activityList.add(activity); 29 } 30 31 // 遍历所有Activity并finish 32 public void exit() { 33 for (Activity activity : activityList) { 34 RLog.i("-aa_aa-", "destroy all activity: " + activity.toString() + " !!!"); 35 activity.finish(); 36 } 37 System.exit(0); 38 } 39 }
2、每一个Activity中的onCreate方法里添加该Activity到MyApplication对象的activityList
MyApplication.getInstance().addActivity(this);
3、结束所有Activity的时候调用exit方法
public void onBackPressed() { MyApplication myApplication = (MyApplication) WheelDemo.this .getApplication(); Log.i("exit app:", "exit ok!"); myApplication.exit(); }