事件分发机制

1.基本用法:

在主线程中使用:

Handler handler = new Handler(){
  @Override
  public void handleMessage(final Message msg) {
    
  }
};
handler.sendMessage(message);
handler.post(runnable);

在其他线程使用:

class LooperThread extends Thread {
    public Handler mHandler;
    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                
            }
        };
        Looper.loop();
    }
}

2.基本原理

2.1Handler:
public class Handler{
	public Handler(Callback callback, boolean async) {
       	mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
	}
	//发送各种消息都是类似操作
	public boolean sendMessage(Message msg){
		msg.target = this;
		return mQueue.enqueueMessage(msg);
	}
	
	//此方法在Loop.loop()中自动调用
	public void dispatchMessage(Message msg) {
		//handler.post(Runnable) 中Runnable就是这里的msg.callback;
		//使用handler.post(Runnable)可以屏蔽handlerMessage方法;
  		if (msg.callback != null) {
    		handleCallback(msg);
  		} else {
    		if (mCallback != null) { 					// 1
      			if (mCallback.handleMessage(msg)) {
        			return;
      			}
    		}
    		//这里的handleMessage就是我们重写Handler时需要覆写的方法
    		handleMessage(msg);
  		}
	}
	
}

注释1处的mCallback是Handler的一个成员变量,它的定义如下:

public interface Callback {
	public boolean handlMessage(Message msg);
}

当不想用继承的方式实现Handler时,可以用new Handler(callback)创建Handler,这个callback会赋值给mCallback

2.2.Looper:
class Looper {
	//单链表队列
	private MessageQueqe mQueue;
	private Thread mThread;
	static ThreadLocal sThreadLocal;
	private Looper(boolean quitAllowed){
		mQueue = new MessageQueue(quitAllowed);
		mThread = Thread.currentThread();
	}
	
	private static void prepare(boolean quitAllowed) {
  		if (sThreadLocal.get() != null) {
    		throw new RuntimeException("Only one Looper may be created per thread");
  		}
  		sThreadLocal.set(new Looper(quitAllowed));
	}
	
	public static Looper myLooper(){
		return sThreadLocal.get();
	}

	public static void loop(){
		final Looper me = myLooper();
		if(me == null) throw RuntimeException();
		final MessageQueue queue = me.mQueue;
		for(;;){
			Message msg = queue.next();
			msg.target.dispatchMessage(msg);
		}
	}
	
	public void quit()
}
其他:

1.Handler内存泄漏:
原因:非静态内部类会持有外部类的引用,所以handler持有Activity,message又持有handler,从而导致内存泄漏;
解决方法:1)使用静态内部类; 2)退出页面之前调用 handler.removeCallbackAndMessage();
2.主线程的Looper创建:

	//ActivityThread
	public static void main(String[] args){
		Looper.prepareMainLooper();
		ActivityThread thread = new ActivityThread();
		if(mainThreadHandler == null){
			mainThreadHandler = thread.getHandler();
		}
		Looper.loop();
	}

且主线程Looper不允许退出

你可能感兴趣的:(事件分发机制)