(六)Handler解析

(六)Handler解析



前言

Android应用程序与传统的PC应用程序一样,都是消息驱动的。也就是说,在Android应用程序主线程中,所有函数都是在一个消息循环中执行的。Android应用程序其它线程,也可以像主线程一样,拥有消息循环。Android应用程序主线程是一个特殊的线程,因为它同时也是UI线程以及触摸屏、键盘等输入事件处理线程。主线程对消息循环很敏感,一旦发生阻塞,就会影响UI的流畅度,甚至发生ANR问题。Handler主要包括四个组成部分:

  • Hanlder: 发送和接收消息
  • Looper: 用于轮询消息队列, 一个线程只能有一个Looper
  • Message: 消息实体
  • MessageQueue: 消息队列用于存储消息和管理消息

一、Looper

1.1 Looper创建

  //ActivityThread.java
    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        ...
        //初始化Looper以及MessageQueue
        Looper.prepareMainLooper();

        ...
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();//开始轮询

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

1.2 Looper.prepareMainLooper()

 //looper.java
  public static void prepareMainLooper() {
        prepare(false);//消息队列可以退出
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }



    private static void prepare(boolean quitAllowed) {
        if (sThreadLocal.get() != null) {//不为空表示当前线程已经创建了Looper
            throw new RuntimeException("Only one Looper may be created per thread");
            //每个线程只能创建一个Looper
        }
        //创建Looper并设置给sThreadLocal, 这样get的时候就不会为null了
        sThreadLocal.set(new Looper(quitAllowed));
    }
    
//创建MessageQueue以及Looper与当前线程的绑定
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
}
    

1.3 Looper.loop()

public static void loop() {
	final Looper me = myLooper();//里面调用了sThreadLocal.get()获得刚才创建的Looper对象
	if (me == null) {
		throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
	}//如果Looper为空则会抛出异常
	final MessageQueue queue = me.mQueue;
	// Make sure the identity of this thread is that of the local process,
	// and keep track of what that identity token actually is.
	Binder.clearCallingIdentity();
	final long ident = Binder.clearCallingIdentity();
	for (;;) {
		//这是一个死循环, 从消息队列不断的取消息
		Message msg = queue.next(); // might block
		if (msg == null) {
		//由于刚创建MessageQueue就开始轮询, 队列里是没有消息的,等到Handler sendMessage enqueueMessage后
		//队列里才有消息
		// No message indicates that the message queue is quitting.
		return;
	} // This must be in a local variable, in case a UI event sets the loggerPrinter logging = me.mLogging;
	if (logging != null) {
		logging.println(">>>>> Dispatching to " + msg.target + " " +msg.callback + ": " + msg.what);
	}
	 msg.target.dispatchMessage(msg);//msg.target就是绑定的Handler, 详见后面Message的部分, Handler开始
	//后面代码省略.....
	msg.recycleUnchecked();
	}
}

二、Hanlde创建

//最常见的创建handler
Handler handler=new Handler(){
	@Override
	public void handleMessage(Message msg) {
	super.handleMessage(msg);
	}
};

//在内部调用 this(null, false);
public Handler(Callback callback, boolean async) {
	//前面省略
	mLooper = Looper.myLooper();//获取Looper, **注意不是创建Looper**!
	if (mLooper == null) {
		throw new RuntimeException("Can't create handler inside thread that has not called Looper.prepare()");
	} 

	mQueue = mLooper.mQueue;//创建消息队列MessageQueue
	mCallback = callback; //初始化了回调接口
	mAsynchronous = async;
}

Looper.myLooper()//这是Handler中定义的ThreadLocal ThreadLocal主要解多线程并发的问题
// sThreadLocal.get() will return null unless you've called prepare().
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

public static @Nullable Looper myLooper() {
	return sThreadLocal.get();
}
sThreadLocal.get() 
//will return null unless you’ ve called prepare(). 这句话告诉我们get可能返回null 除非先调用prepare()方法创建Looper。 

三、Message创建

一般可以使用new Message来创建Message,但还有更好的创建方式 Message.obtain。 因为可以检查是否有可以复用的Message,用过复用避免过多的创建、 销毁Message对象达到优化内存和性能的目地。

public static Message obtain(Handler h) {
	Message m = obtain();//调用重载的obtain方法
	m.target = h;//并绑定的创建Message对象的handler
	return m;
}

    public static Message obtain() {
        synchronized (sPoolSync) {//sPoolSync是一个Object对象, 用来同步保证线程安全
            if (sPool != null) {//sPool是就是handler dispatchMessage 后 通过recycleUnchecked回收用以复用的Message
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

四、发送消息

Handler发送消息的重载方法很多, 但是主要只有2种。 sendMessage(Message)和 sendMessage方法通过一系列重载方法的调用,sendMessage调用sendMessageDelayed, 继续调用sendMessageAtTime, 继续调用enqueueMessage, 继续调用messageQueue的enqueueMessage方法, 将消息保存在了消息队列中, 而最终由Looper取出, 交给Handler的dispatchMessage进行处理。

public void dispatchMessage(Message msg) {
	if (msg.callback != null) {//callback在message的构造方法中初始化或者使用handler.post(Runnable)时候才不为空
		handleCallback(msg);
	} else {
		if (mCallback != null) {//mCallback是一个Callback对象, 通过无参的构造方法创建出来的handler, 该属性为null, 此段不执行
			if (mCallback.handleMessage(msg)) {
				return;
			}
		}
	 handleMessage(msg);//最终执行handleMessage方法
	}
}
private static void handleCallback(Message message) {
	message.callback.run();
}

五、处理消息

在handleMessage(Message)方法中, 我们可以拿到message对象, 根据不同的需求进行处理, 整个Handler机制的流程就结束了。

六、MessageQueue

6.1 enqueueMessage(消息入库)

 boolean enqueueMessage(Message msg, long when) {
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }

        synchronized (this) {//锁开始
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

6.2 next(消息出库)

 Message next() {
        ...
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;
        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }

            nativePollOnce(ptr, nextPollTimeoutMillis);
			//这样由于synchronized( this) 作用范围是所有 this正在访问的代码块都会有保护作用
			//也就是它可以保证 next函数和 enqueueMessage函数能够实现互斥。 这样才能真正的保证多线程访问的时候messagequeue的有序进行
            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                Message prevMsg = null;
                Message msg = mMessages;
                if (msg != null && msg.target == null) {
                    // Stalled by a barrier.  Find the next asynchronous message in the queue.
                    do {
                        prevMsg = msg;
                        msg = msg.next;
                    } while (msg != null && !msg.isAsynchronous());
                }
                if (msg != null) {
                    if (now < msg.when) {
                        // Next message is not ready.  Set a timeout to wake up when it is ready.
                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                    } else {
                        // Got a message.
                        mBlocked = false;
                        if (prevMsg != null) {
                            prevMsg.next = msg.next;
                        } else {
                            mMessages = msg.next;
                        }
                        msg.next = null;
                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        return msg;
                    }
                } else {
                    // No more messages.
                    nextPollTimeoutMillis = -1;
                }

                // Process the quit message now that all pending messages have been handled.
                if (mQuitting) {
                    dispose();
                    return null;
                }

                // If first time idle, then get the number of idlers to run.
                // Idle handles only run if the queue is empty or if the first message
                // in the queue (possibly a barrier) is due to be handled in the future.
                if (pendingIdleHandlerCount < 0
                        && (mMessages == null || now < mMessages.when)) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount <= 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf(TAG, "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

总结

handler机制就是一个传送带的运转机制。
1) MessageQueue就像履带。
2) Thread就像背后的动力, 就是我们通信都是基于线程而来的。
3) 传送带的滚动需要一个开关给电机通电, 那么就相当于我们的loop函数, 而这个loop里面的for循环就会带着不断的滚动, 去轮询messageQueue
4) Message就是 我们的货物了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值