Android 随时随地的退出程序

1.建立一个ActivityCollector来管理所有的Activity

public class ActivityCollector {
    public static List<Activity> activities = new ArrayList<Activity>();
    public static void addActivity(Activity activity){
        activities.add(activity);
    }
    public static void removeActivity(Activity activity){
        activities.remove(activity);
    }
    public static void finishAll(){
        for (Activity activity: activities) {
            if (!activity.isFinishing()){
                activity.finish();
            }
        }
    }
};

新建一个BaseActivity继承Activity,调用控制器的方法

public class BaseActivity  extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Log.d("BaseActivity", getClass().getSimpleName());
        ActivityCollector.addActivity(this);
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }
}

让所有的Activity都继承这个基类,并绑定按钮调用ActivityCollector.finishAll()方法

比如在Main2Activity里

public class Main2Activity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("ThirdActivity", "Task id is " + getTaskId());
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main2);
        Button button3 = (Button) findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                ActivityCollector.finishAll();
                //android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
    }

这样,我们在第二个Activity中点击Button3,便可以退出所有的Activity.

posted @ 2016-06-01 17:40  爪哇见习  阅读(289)  评论(0编辑  收藏  举报