android 完全退出实现
实现方法是在application中定义一个集合存储所有的Activity对象,在Activity创建时添加进集合中,在程序退出时,finish掉所有的Activity即可。
步骤如下:
1.自定义Application,MyApplication.java代码如下:
1 public class MyApplication extends Application{ 2 private static ArrayList<Activity> activityList; 3 private static MyApplication sInstance; 4 @Override 5 public void onCreate() { 6 super.onCreate(); 7 activityList=new ArrayList<Activity>(); 8 sInstance=this; 9 } 10 public static MyApplication getInstance(){ 11 return sInstance; 12 } 13 public void addActivity(Activity activity) { 14 activityList.add(activity); 15 } 16 public void exit(){ 17 for (Activity activity : activityList) { 18 activity.finish(); 19 } 20 System.exit(0); 21 } 22 }
2.定义Activity基类BaseActivity,所有的Activity继承BaseActivity,Activity创建时添加Activity对象到Application中的集合中,BaseAcivity.java代码如下:
1 public class BaseActivity extends Activity{ 2 @Override 3 protected void onCreate(Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 MyApplication.getInstance().addActivity(this); 6 } 7 }
3.在程序退出是调用MyApplication中exit()方法即可完全退出,代码如下:
MyApplication.getInstance().exit();