欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android的优化BaseActivity统一管理Activity

程序员文章站 2024-03-24 12:29:22
...

用一个集合管理所有的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<BaseActivity> mActivities = new LinkedList<BaseActivity>();
	
	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<BaseActivity> copy;
		
		//同步锁,线程安全
		synchronized (mActivities) {
			copy = new LinkedList<BaseActivity>(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高级进阶