1.自定义一个application,并将所有的activity装入activitylist里面,在 AndroidManifest.xml中注册 <application android:name=".ExitAll"></application>
- package com.dragon;
- import java.util.LinkedList;
- import java.util.List;
- import android.app.Activity;
- import android.app.Application;
- public class ExitAll extends Application {
- private List<Activity> activityList = new LinkedList<Activity>();
- private static ExitAll instance;
- private ExitAll() {
- }
- // 单例模式中获取唯一的MyApplication实例
- public static ExitAll getInstance() {
- if (null == instance) {
- instance = new ExitAll();
- }
- return instance;
- }
- // 添加Activity到容器中
- public void addActivity(Activity activity) {
- activityList.add(activity);
- }
- // 遍历所有Activity并finish
- public void exit() {
- for (Activity activity : activityList) {
- activity.finish();
- }
- System.exit(0);
- }
- @Override
- public void onCreate() {
- // TODO Auto-generated method stub
- System.out.println("ExitAll创建");
- super.onCreate();
- }
- }
2.在每一个activity加入
- ExitAll.getInstance().addActivity(OneActivity.this); //当前activity
3.在想结束的activity中加入
- ExitAll ea=ExitAll.getInstance();
一般来说,在Android退出时,有的Activity可能没有被关闭。为了在Android退出时关闭所有的Activity,这里给出了以下的类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
//关闭Activity的类
public
class
CloseActivityClass{
public
static
List<Activity> activityList =
new
ArrayList<Activity>();
public
static
void
exitClient(Context ctx)
{
// 关闭所有Activity
for
(
int
i =
0
; i < activityList.size(); i++)
{
if
(
null
!= activityList.get(i))
{
activityList.get(i).finish();
}
}
ActivityManager activityMgr = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE );
activityMgr.restartPackage(ctx.getPackageName());
System.exit(
0
);
}
}
|
然后在应用中每一个Activity的onCreate(Bundle savedInstanceState)方法中增加一句:
1
|
CloseActivityClass.activityList.add(
this
);
|
在应用退出时:
1
|
CloseActivityClass.exitClient(MainActivity.
this
);
|
这样,当退出应用时就可以将该应用的所有Activity彻底关闭。