使用Application维护管理Activity列表(用于退出整个程序,结束所有Activity)

先自定义一个继承自Application的类:


import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Application;

public class MyApplication extends Application {
	private List  activitys;
	//在Activity的OnCreate方法中调用,添加Activity实例
    public void addActivity(Activity act) {
    	if(activitys==null)
    	{
    		activitys = new ArrayList();
    	}
    	activitys.add(act);  
    }
    //退出程序时调用,调用所有Activity的finish方法
    public void finishAll() {  
        for (Activity act : activitys) {  
            if (!act.isFinishing()) {  
                act.finish();  
            }  
        }  
        activitys = null;  
    }  
}

修改AndroidManifest.xml中Application标签,设置android:name为我们自定义的MyApplication


    
        
            
                
                
            
        
        
    

在每个Activity的OnCreate方法里把当前的Activity实例添加到Application里的列表中:


MyApplication application = (MyApplication) this.getApplication();
application.addActivity(this);

退出整个程序:


MyApplication application = (MyApplication) this.getApplication();
application.finishAll();

© 2012, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记