1.Handler是Android消息机制的上层接口,通过它可以轻松的将一个任务切换到Handler所在的线程中去执行。
2.更新UI仅仅是Handler的一个特殊使用场景:有时候需要在子线程中进行耗时的I/O操作,可能是读取文件或访问网络,当耗时操作完成以后需要在UI上进行一些改变,这时通过Handler就可以将更新UI的操作切换到主线程中去执行。
3.Android的消息机制主要是指Handler的运行机制,Handler运行需要底层的MessageQueue和Looper的支撑。
MessageQueue:消息队列,采用单链表的数据结构存储消息列表,以队列的形式对外提 供插入和删除工作.
Lopper:以无限循环的形式去查找是否有新消息,有就处理,没有就一直等待。
Thread:不是线程,作用是可以在每个线程中存储数据。
4.Handler创建的时候会采用当前的Looper来构造消息循环系统,Handler内部如何获取到当前线程的Looper?使用ThreadLocal,ThreadLocal可以在不同的线程中互不干扰地存储并提供数据,通过ThreadLocal可以获取每个线程的Looper。
5.线程是默认没有Looper的,如果需要使用Handler就必须为线程创建Looper。
6.经常提到的主线程也叫UI线程,就是ActivityThread,ActivityThread被创建时就会初始化Looper,所以,在主线程中默认可以使用Handler。
1.Android的消息机制:Handler的运行机制和Handler所附带的MessageQueue和Looper的工作过程。
2.Handler:将一个任务切换到指定的线程中去执行。
3.Android不在主线程中进行耗时操作:会导致程序无法响应即ANR。我们需要从服务端拉取一些信息将其显示再UI上,这时在子线程中拉取,拉取完后不能在子线程中直接访问UI,提供Handler,解决子线程中无法访问UI的矛盾。
4.不允许在子线程中访问UI:Android的UI控件不是线程安全的,如果在多线程中并发访问可能会导致UI控件处于不可预期的状态。
5.不对UI控件的访问加上锁机制:上锁机制会让UI访问的逻辑变得复杂;锁机制会降低UI访问的效率,阻塞某些线程的执行。
最简单且高效的方法就是采用单线程模型来处理UI操作,通过Handler切换一下UI访问的执行线程。
1.Handler创建时会采用当前线程的Looper来构建内部的消息循环系统,若当前线程没有Looper,就会报错。
解决:1.为当前线程创建Looper 2.在一个又Looper的线程中创建Handler
2.Handler创建完毕后,内部的Looper和MessageQueue就可以和Handler一起协同工作。
· 通过Handler的post方法将一个Runnable投递到Handler内部Looper中去处理
· 通过Handler的send方法发送一个消息,这个消息同样在Looper中去处理
· send方法:调用MessageQueue的enqueueMessage方法将这个消息放入消息队列中,Looper发现有新消息时,就会处理,最终消息中的Runnable或Handler的handleMessage方法就会被调用。Looper是运行在创建Handler所在的线程中,这样Handler中的业务逻辑就会被切换到创建Handler所在的线程中取执行了。
1.ThreadLocal是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,数据存储后,只有在指定线程中可以获取到存储数据,用来保证我们在不同线程中获取数据时,拿到的是自己线程中存储的数据
2.当某些数据是以线程为作用域并且不同线程有不同的数据副本时,可以考虑采用ThreadLocal。
使用场景:
1.Handler需要获取当前线程的Looper,Looper的作用域就是线程,并且不同线程具有不同的Looper,通过ThreadLocal就可以轻松实现Looper在线程中的存取。
2.复杂逻辑下的对象传递,如监听器。有时一个线程中的任务过于复杂,如函数调用栈比较深以及代码入口的多样性,这时有需要监听器能贯穿整个线程的执行过程,采用ThreadLocal,采用ThreadLocal可以让监听器作为线程内的全局对象,每个监听对象都在自己的线程内部存储,在线程内部只要通过get方法就可以获取到监听器。
ThreadLocalMap:
是ThreadLocal的内部类,其实,ThreadLocal并不存储数据,只是提供对ThreadLocalMap的操作,ThreadLocalMap才是真正存数据的地方。Thread为每个线程创建一个ThreadLocalMap,ThreadLocalMap里面有一个Entry类型的数组,用来存每个Entry。Entry是ThreadLocalMap里面的一个静态内部类,它通过自己的构造函数将ThreadLocal和数据按照键值对的形式存下来,Entry在数组中如何存储,是根据ThreadLocal的哈希值与数组长度-1进行与运算。
private void set(ThreadLocal<?> key, Object value) {
// We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.
Entry[] tab = table;
int len = tab.length;
int i = key.threadLocalHashCode & (len-1);
for (Entry e = tab[i];
e != null;
e = tab[i = nextIndex(i, len)]) {
ThreadLocal<?> k = e.get();
if (k == key) {
e.value = value;
return;
}
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
用 i 在这个数组中取值,如果有值并且得到的 key 就是你要设置value的key,就直接设置值然后返回,有值但 key 为 null 了,就更新为新的。那如果有值,key也不为 null,也不与新的 key 相同呢?那就将 i + 1;直到找到一个符合的位置。
总结:每个线程会维护属于自己线程的ThreaedLocalMap,存数据使用到的ThreadLocal是要存数据的键,根据这个键在不同的线程中的ThreadLocalMap取到不同的值,形成数据隔离。
ThreadLocal的get方法:
public T get() {
Thread t = Thread.currentThread(); //先拿到当前线程 t
ThreadLocalMap map = getMap(t); //再通过 t 取到当前线程中的ThreadLocalMap
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this); //在ThreadLocalMap中通过 this 也就是ThreadLocal取到对应的 e
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value; //调用 e.value 取到想要的值
return result;
}
}
return setInitialValue();
}
set方法:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
消息队列在Android中指的是MessageQueue,MessageQueue主要有两个操作:插入和读取,对应的方法分别为enqueueMessage和next。
enqueueMessage:往消息队列中插入一条消息
next:从消息队列中取出一条消息并将其从消息队列中移除
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
synchronized (this) {
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
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;
}
1.从头到尾遍历这个单链表,将 msg.next 设置为 null,再将 msg 放到链表的最末尾
2.特殊设置了 when 的话,会找到合适的位置将其插入
3.单链表是有顺序的,它是按照处理时间顺序从近到远排序
enqueueMessage的主要操作就是单链表的插入
取的动作是发生在 Looper 的 loop 中,它调用的是 MessageQueue 中的 next() 方法
Message next() {
// Return here if the message loop has already quit and been disposed.
// This can happen if the application tries to restart a looper after quit
// which is not supported.
final long ptr = mPtr;
if (ptr == 0) {
//当消息循环已经退出,则直接返回
return null;
}
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
// Try to retrieve the next message. Return if found.
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
//当消息的Handler为空时,则查询异步消息
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; //成功地获取MessageQueue中的下一条即将要执行的消息
}
} else {
// No more messages.
//没有消息
nextPollTimeoutMillis = -1;
}
// Process the quit message now that all pending messages have been handled.
//消息正在退出,返回null
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.
//没有idle handlers 需要运行,则循环并等待
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.
//只有第一次循环时,会运行idle handlers,执行完成后,重置pendingIdleHandlerCount为0.
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.
//重置idle handler个数为0,以保证不会再次重复运行
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.
//当调用一个空闲handler时,一个新message能够被分发,因此无需等待可以直接查询pending message.
nextPollTimeoutMillis = 0;
}
}
next方法是一个无限循环的方法,若消息队列中没有消息,那么next方法会一直阻塞在这里,有新消息时,next方法会返回这条消息并将其从单链表中移除。
Looper在Android的消息机制中扮演着消息循环的角色,会不停的从MessageQueue中查看是否有新消息,有新消息就处理,否则就会一直阻塞在那里。Looper 负责不断的调用 MessageQueue 的 next() 方法取出消息并交给 Handler 处理。
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed); //创建一个MessageQueue即消息队列
mThread = Thread.currentThread(); //将当前线程的对象保存起来
}
Looper.prepare()在每个线程只允许执行一次,通过Looper.prepare()为当前线程创建一个Looper,通过Looper.loop()来开启消息循环。
new Thread("Thread#2"){
@Override
public void run(){
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
};
}.start();
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//创建Looper对象,并保存到当前线程的TLS区域
sThreadLocal.set(new Looper(quitAllowed));
}
prepareMainLooper()方法,该方法主要在ActivityThread类中使用。
@Deprecated
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
getMainLooper()方法,通过它可在任何一个地方获取到主线程的Looper。
quit():直接退出Looper
quitSafely():设定一个退出标记,把消息队列中的已有消息处理完毕后安全退出
public void quit() {
mQueue.quit(false);
}
public void quitSafely() {
mQueue.quit(true);
}
Loop()
只有调用了loop后,消息循环才会真正起作用
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
if (me.mInLoop) {
Slog.w(TAG, "Loop again would have the queued messages be executed"
+ " before this one completed.");
}
me.mInLoop = true;
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();
// Allow overriding a threshold with a system prop. e.g.
// adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
final int thresholdOverride =
SystemProperties.getInt("log.looper."
+ Process.myUid() + "."
+ Thread.currentThread().getName()
+ ".slow", 0);
boolean slowDeliveryDetected = false;
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//唯一跳出循环的方式:MessageQueue的next方法返回了null
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
// Make sure the observer won't change while processing a transaction.
final Observer observer = sObserver;
final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
Object token = null;
if (observer != null) {
token = observer.messageDispatchStarting();
}
long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
try {
msg.target.dispatchMessage(msg);
if (observer != null) {
observer.messageDispatched(token, msg);
}
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} catch (Exception exception) {
if (observer != null) {
observer.dispatchingThrewException(token, msg, exception);
}
throw exception;
} finally {
ThreadLocalWorkSource.restore(origWorkSource);
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, "Drained");
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
// Make sure that during the course of dispatching the
// identity of the thread wasn't corrupted.
final long newIdent = Binder.clearCallingIdentity();
if (ident != newIdent) {
Log.wtf(TAG, "Thread identity changed from 0x"
+ Long.toHexString(ident) + " to 0x"
+ Long.toHexString(newIdent) + " while dispatching to "
+ msg.target.getClass().getName() + " "
+ msg.callback + " what=" + msg.what);
}
msg.recycleUnchecked();
}
}
Handler的作用是投递消息和处理消息的,它会绑定一个Looper,一个线程可以有多个 Handler,但只会有一个Looper
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
public boolean sendMessageAtTime(@NonNull Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
Handler发消息,向消息队列中插入了一条消息,MessageQueue的next方法会返回这条消息给Looper,Looper收到消息后开始处理,最终消息由Looper交由Handler处理,即Handler的dispatchMessage方法会被调用,这时Handler进入处理消息的阶段。
public void dispatchMessage(@NonNull Message msg) {
//检查Message的callback是否为null
if (msg.callback != null) {
//不为null就通过handleCallback来处理消息
//Message的callback是一个Runnable对象
//实际上就是Handler的post方法所传递的Runnable参数
handleCallback(msg);
} else {
//检查mCallback是否为null
if (mCallback != null) {
//不为null就调用mCallback的handleMessage方法处理消息
if (mCallback.handleMessage(msg)) {
return;
}
}
//最后调用Handler的handleMessage方法处理具体的消息
handleMessage(msg);
}
}
handleCallback
private static void handleCallback(Message message) {
message.callback.run();
}
Callback是个接口:
/**
* Callback interface you can use when instantiating a Handler to avoid
* having to implement your own subclass of Handler.
*/
public interface Callback {
/**
* @param msg A {@link android.os.Message Message} object
* @return True if no further handling is desired
*/
boolean handleMessage(@NonNull Message msg);
}
public Handler(@Nullable Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper(); //Handler中的Looper通过Looper.myLooper()绑定
if (mLooper == null) {
//如果当前线程没有Looper,会抛出这个异常。
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}