Handler总结图
Handler简单的使用
我们一般使用handler发送消息,只需要两步,首先是创建一个Handler对象,并重写handleMessage方法,就是上图中的3(Message.target.handleMeesage),然后需要消息通信的地方,通过Handler的sendMessage方法发送消息(这里我们创建了一个子线程,模拟子线程向主线程发送消息)。代码如下:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private Handler mHandler;
private Button btnSendeToMainThread;
private static final int MSG_SUB_TO_MAIN= 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1.创建Handler,并重写handleMessage方法
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 处理消息
switch (msg.what) {
case MSG_SUB_TO_MAIN:
// 打印出处理消息的线程名和Message.obj
Log.e(TAG, "接收到消息: " + Thread.currentThread().getName() + ","+ msg.obj);
break;
default:
break;
}
}
};
btnSendeToMainThread = (Button) findViewById(R.id.btn_sendto_mainthread);
btnSendeToMainThread .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 创建一个子线程,在子线程中发送消息
new Thread(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain();
msg.what = MSG_SUB_TO_MAIN;
msg.obj = "这是一个来自子线程的消息";
// 2.发送消息
mHandler.sendMessage(msg);
}
}).start();
}
});
}
}
在log中会打印出“这是一个来自子线程的消息”
这样就完成子线程向主线程发送消息,辣么,如果想要主线程向子线程发送消息呢?是否也只要在子线程中创建Handler对象,然后在主线程中拿到子线程的Handler以后,调用sendMessage发送消息。在onCreate中添加如下代码:
// 创建一个子线程,并在子线程中创建一个Handler,且重写handleMessage
new Thread(new Runnable() {
@Override
public void run() {
subHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 处理消息
switch (msg.what) {
case MSG_MAIN_TO_SUB:
Log.e(TAG, "接收到消息: " + Thread.currentThread().getName() + ","+ msg.obj);
break;
default:
break;
}
}
};
}
}).start();
btnSendToSubThread = (Button) findViewById(R.id.btn_sendto_subthread);
btnSendToSubThread.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message msg = Message.obtain();
msg.what = MSG_MAIN_TO_SUB;
msg.obj = "这是一个来自主线程的消息";
// 主线程中发送消息
subHandler.sendMessage(msg);
}
});
我们点击按钮时,发现并没有成功,并且报出了如下的错误信息:
Can' t create handler inside thread that has not called Looper. prepare()
原因也说得很清楚了,说的是我们不能在一个没有调用Looper.prepare()的线程去创建Handler对象。那为什么主线程我们不需要去手动调用Looper.prepare()就可以直接使用Handler呢?原来是启动App时,系统帮我们创建好了,App的入口,是ActivityThread.main方法,代码如下:
public static void main(String[] args) {
// 不相干代码
......
// 1.调用Looper.prepareMainLooper,其实也就是调用的Looper.loop,初始化Looper、MessageQueue等
Looper.prepareMainLooper();
// 2.创建ActivityThread的同时,初始化了成员变量Handler mH
ActivityThread thread = new ActivityThread();
thread.attach(false);
//
if (sMainThreadHandler == null) {
// 把创建的Handler mH赋值给sMainThreadHandler
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
// 3.调用Looper.loop()方法,开启死循环,从MessageQueue中不断取出Message来处理
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
看样子,创建Handler还是需要调用Looper.prepare的,我们平常在主线程不需要手动调用,是因为系统在启动App时,就帮我们调用了。并且还需要调用Looper.loop方法,这个方法后面我们会讲到。所以使用Handler通信之前需要有以下三步:
- 调用Looper.prepare()
- 创建Handler对象
- 调用Looper.loop()
那按照这个套路,我们完善下之前的代码,其实就是在子线程中创建Handler之前调用Looper.prepare(),之后调用Looper.loop()方法,如下:
// 创建一个子线程,并在子线程中创建一个Handler,且重写handleMessage
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
subHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 处理消息
switch (msg.what) {
case MSG_MAIN_TO_SUB:
Log.e(TAG, "接收到消息: " + Thread.currentThread().getName() + ","+ msg.obj);
break;
default:
break;
}
}
};
Looper.loop();
}
}).start();
在log中会再次打印出“这是一个来自子线程的消息”
现在就可以使用Handler在主线程向子线程发送消息了,且可以看到,是在子线程中处理消息的。
Handler消息的发送
我们都知道当调用 Handler 发送消息的时候,不管是调用 sendMessage、sendEmptyMessage、sendMessageDelayed 还是其他发送一系列方法。最终都会调用 sendMessageDelayed(Message msg, long delayMillis) 方法。
public final boolean sendMessageDelayed(Message msg, long delayMillis){
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
该方法会调用 sendMessageAtTime() 方法。其中第二个参数是执行消息的时间,是通过从开机到现在的毫秒数(手机睡眠的时间不包括在内)+ 延迟执行的时间。这里不使用 System.currentTimeMillis() ,是因为该时间是可以修改的。会导致延迟消息等待时间不准确。该方法内部会调用 sendMessageAtTime() 方法,我们接着往下走。
public boolean sendMessageAtTime(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);
}
这里获取到线程中的 MessageQueue 对象 mQueue (在构造函数通过Looper获得的),并调用 enqueueMessage() 方法,enqueueMessage() 方法最终内部会调用 MessageQueue 的 enqueueMessage() 方法,那现在我们就直接 MessageQueue中 把消息加入消息队列中的方法。
面试汇总
- 主线程的looper呢??
- 为什么有死循环呢?这种写法科学吗?不会oom吗??
- Handler机制还还还有什么其他的用处或者实际应用吗?
- 同步屏障机制是什么,有什么用呢?
- IdleHandler是什么,有什么用呢?
(你想要的答案都在楼下哦) www.jianshu.com/p/a07bd3e28… 内存泄漏??(这个帮助你更深刻的理解内存泄漏) juejin.cn/post/692198…
Handler发送消息的源码解析
经过上面的知识点讲解,大家应该都大致了解了Handler内部原理,最后我们就跟随源码再复习一遍。 我们之前了解到,其实Handler真正做事其实就是两个方法:
- sendEmptyMessage(Handler发送消息)
- loop (Looper开始循环获取消息)
sendMessage 上源码:
public final boolean sendMessage(@NonNull Message msg) {
return sendMessageDelayed(msg, 0);
}
public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
}
public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
}
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);
}
可以看到,不管是发送的什么消息,最后都会走到这个enqueueMessage方法中,那我们就继续看看enqueueMessage方法:
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);
}
enqueueMessage方法有两个重要的点:
- msg.target = this,指定了消息的target对象为handler本身
- queue.enqueueMessage(msg, uptimeMillis),执行了MessageQueue的enqueueMessage方法。
ok,接着往下看:
//MessageQueue.java
boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
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;
}
enqueueMessage 这个方法主要做了两件事:
1、插入消息,msg。通过一个循环,找出msg应该插入的位置(按照时间排序),然后插入msg到mMessages(消息队列)
2、唤醒消息队列。消息队列在没有消息的时候,会阻塞在queue.next()方法这里,所以来了消息就要唤醒线程。这里的阻塞和唤醒主要依靠底层的epoll 机制
既然有了消息,那么Looper那端就要取消息了,怎么取的?就是我们要说的第二个重要方法loop
loop
//Looper.java
public static void loop() {
final Looper me = myLooper();
final MessageQueue queue = me.mQueue;
for (;;) {
Message msg = queue.next(); // might block
// 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);
}
try {
msg.target.dispatchMessage(msg);
} catch (Exception exception) {
throw exception;
} finally {
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
}
}
/**
* Handle system messages here.
*/
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
这里截取了部分代码,可以看到,loop方法通过一个死循环,不断的从MessageQueue获取消息,并且通过msg.target的dispatchMessage方法进行处理,target上文说过也就是消息对应的Handler。 而dispatchMessage方法最后也会调用到handler的handleMessage方法了。至此,流程已走通。
ok,还剩最后一个重要的点没说了。就是到底MessageQueue是怎么取出消息的呢?
- 死循环获取消息
- 遇到同步屏障消息,就优先处理异步消息
- 队列空闲时就开启IdleHandler机制处理任务。
代码如下:
//MessageQueue.java
Message next() {
for (;;) {
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;
}
// 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);
}
}
}
}
}
至此,Handler的大概已经了解的差不多了,是不是觉得Handler太神奇了,你也忍不住想去好好看看它的源码了呢?也许还有一些功能没被利用起来;
如果有些地方说的有错误或者不是太完美,还请指正!Thanks♪(・ω・)ノ