Android的优化BaseActivity统一管理Activity

用一个集合管理所有的activity,销毁的时候,同时杀死当前的进程,来清理所有的内容

BaseActivity.java

package com.ldw.market;

/*
 * 基类Activity实现ActionBar的一些共性方法
 */
import java.util.LinkedList;
import java.util.List;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

public class BaseActivity extends ActionBarActivity {
	// 管理运行的所有的Activity
	public final static List mActivities = new LinkedList();
	
	private killAllReceiver receiver;
	private class KillAllReceiver extends BroadcastReceiver{
		
		@Override
		public void onReceiver(Context context, Intent intent){
			finish();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		receiver = new KillAllReceiver();
		IntentFilter filter = new IntentFilter("com.ldw.marketm.killall");
		registerReceiver(receiver, filter);
		
		
		//同步锁,线程安全
		synchronized (mActivities) {
			// 初始化的时候往链表中初始化Activity,添加Activity
			mActivities.add(this);
		}

		init();
		initView();
		initActionBar();
	}

	@Override
	protected void onDestroy() {
		// 销毁的时候remove掉
		super.onDestroy();
		synchronized (mActivities) {
			mActivities.remove(this);
		}
		if(receiver!=null){
			unregisterReceiver(receiver);
			receiver=null;
		}
	}

	// 退出的时候关闭所有的Activity
	public void killAll() {
		// 复制了一份mActivities 集合
		List copy;
		
		//同步锁,线程安全
		synchronized (mActivities) {
			copy = new LinkedList(mActivities);
		}
		for (BaseActivity activity : copy) {
			activity.finish();
		}
		// 杀死当前的进程
		android.os.Process.killProcess(android.os.Process.myPid());
	}

	protected void initActionBar() {
		// TODO Auto-generated method stub

	}

	protected void initView() {
		// TODO Auto-generated method stub

	}

	protected void init() {
		// TODO Auto-generated method stub

	}
}

 

你可能感兴趣的:(Android高级进阶)