本篇内容主要讲解“Handler的原理有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Handler的原理有哪些”吧!
成都创新互联公司主要从事网站建设、网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务裕华,十余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:18980820575
开头需要建立个handler作用的总体印象,下面画了一个总体的流程图

从上面的流程图可以看出,总体上是分几个大块的
Looper.prepare()、Handler()、Looper.loop() 总流程
收发消息
分发消息
相关知识点大概涉及到这些,下面详细讲解下!
需要详细的查看该思维导图,请右键下载后查看

先来看下使用,不然源码,原理图搞了一大堆,一时想不起怎么用的,就尴尬了
使用很简单,此处仅做个展示,大家可以熟悉下
演示代码尽量简单是为了演示,关于静态内部类持有弱引用或者销毁回调中清空消息队列之类,就不在此处展示了
来看下消息处理的分发方法:dispatchMessage(msg)
Handler.java
...
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
...从上面源码可知,handler的使用总的来说,分俩大类,细分三小类
收发消息一体
handleCallback(msg)
收发消息分开
mCallback.handleMessage(msg)
handleMessage(msg)
handleCallback(msg)
使用post形式,收发都是一体,都在post()方法中完成,此处不需要创建Message实例等,post方法已经完成这些操作
public class MainActivity extends AppCompatActivity {
private TextView msgTv;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTv = findViewById(R.id.tv_msg);
//消息收发一体
new Thread(new Runnable() {
@Override public void run() {
String info = "第一种方式";
mHandler.post(new Runnable() {
@Override public void run() {
msgTv.setText(info);
}
});
}
}).start();
}
}实现Callback接口
public class MainActivity extends AppCompatActivity {
private TextView msgTv;
private Handler mHandler = new Handler(new Handler.Callback() {
//接收消息,刷新UI
@Override public boolean handleMessage(@NonNull Message msg) {
if (msg.what == 1) {
msgTv.setText(msg.obj.toString());
}
//false 重写Handler类的handleMessage会被调用, true 不会被调用
return false;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTv = findViewById(R.id.tv_msg);
//发送消息
new Thread(new Runnable() {
@Override public void run() {
Message message = Message.obtain();
message.what = 1;
message.obj = "第二种方式 --- 1";
mHandler.sendMessage(message);
}
}).start();
}
}重写Handler类的handlerMessage(msg)方法
public class MainActivity extends AppCompatActivity {
private TextView msgTv;
private Handler mHandler = new Handler() {
//接收消息,刷新UI
@Override public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
msgTv.setText(msg.obj.toString());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTv = findViewById(R.id.tv_msg);
//发送消息
new Thread(new Runnable() {
@Override public void run() {
Message message = Message.obtain();
message.what = 1;
message.obj = "第二种方式 --- 2";
mHandler.sendMessage(message);
}
}).start();
}
}大家肯定有印象,在子线程和子线程的通信中,就必须在子线程中初始化Handler,必须这样写
prepare在前,loop在后,固化印象了
new Thread(new Runnable() {
@Override public void run() {
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
});为啥主线程不需要这样写,聪明你肯定想到了,在入口出肯定做了这样的事
ActivityThread.java
...
public static void main(String[] args) {
...
//主线程Looper
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
//主线程的loop开始循环
Looper.loop();
...
}
...为什么要使用prepare和loop?我画了个图,先让大家有个整体印象

上图的流程,鄙人感觉整体画的还是比较清楚的
总结下就是
Looper.prepare():生成Looper对象,set在ThreadLocal里
handler构造函数:通过Looper.myLooper()获取到ThreadLocal的Looper对象
Looper.loop():内部有个死循环,开始事件分发了;这也是最复杂,干活最多的方法
具体看下每个步骤的源码,这里也会标定好链接,方便大家随时过去查看
Looper.prepare()
可以看见,一个线程内,只能使用一次prepare(),不然会报异常的
Looper.java
...
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");
}
sThreadLocal.set(new Looper(quitAllowed));
}
...Handler()
这里通过Looper.myLooper() ---> sThreadLocal.get()拿到了Looper实例
Handler.java
...
@Deprecated
public Handler() {
this(null, false);
}
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();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
...Looper.java
...
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
...Looper.loop():该方法分析,在分发消息里讲
精简了大量源码,详细的可以点击上面方法名
Message msg = queue.next():遍历消息
msg.target.dispatchMessage(msg):分发消息
msg.recycleUnchecked():消息回收,进入消息池
Looper.java
...
public static void loop() {
final Looper me = myLooper();
...
final MessageQueue queue = me.mQueue;
...
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
...
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);
}
}
....
msg.recycleUnchecked();
}
}
...收发消息的操作口都在Handler里,这是我们最直观的接触的点
下方的思维导图整体做了个概括

在说发送和接受消息之前,必须要先解释下,Message中一个很重要的属性:when
when这个变量是Message中的,发送消息的时候,我们一般是不会设置这个属性的,实际上也无法设置,只有内部包才能访问写的操作;将消息加入到消息队列的时候会给发送的消息设置该属性。消息加入消息队列方法:enqueueMessage(...)
在我们使用sendMessage发送消息的时候,实际上也会调用sendMessageDelayed延时发送消息发放,不过此时传入的延时时间会默认为0,来看下延时方法:sendMessageDelayed
public final boolean sendMessageDelayed(@NonNull Message msg, long delayMillis) {
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}这地方调用了sendMessageAtTime方法,此处!做了一个时间相加的操作:SystemClock.uptimeMillis() + delayMillis
SystemClock.uptimeMillis():这个方法会返回一个毫秒数值,返回的是,打开设备到此刻所消耗的毫秒时间,这很明显是个相对时间刻!
delayMillis:就是我们发送的延时毫秒数值
后面会将这个时间刻赋值给when:when = SystemClock.uptimeMillis() + delayMillis
说明when代表的是开机到现在的一个时间刻,通俗的理解,when可以理解为:现实时间的某个现在或未来的时刻(实际上when是个相对时刻,相对点就是开机的时间点)
发送消息涉及到俩个方法:post(...)和sendMessage(...)
post(Runnable):发送和接受消息都在post中完成
sendMessage(msg):需要自己传入Message消息对象
看下源码
此方法给msg的target赋值当前handler之后,才进行将消息添加的消息队列的操作
msg.setAsynchronous(true):设置Message属性为异步,默认都为同步;设置为异步的条件,需要手动在Handler构造方法里面设置
使用post会自动会通过getPostMessage方法创建Message对象
在enqueueMessage中将生成的Message加入消息队列,注意
Handler.java
...
//post
public final boolean post(@NonNull Runnable r) {
return sendMessageDelayed(getPostMessage(r), 0);
}
//生成Message对象
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
//sendMessage方法
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);
}
///将Message加入详细队列
private boolean enqueueMessage(@NonNull MessageQueue queue, @NonNull Message msg,
long uptimeMillis) {
//设置target
msg.target = this;
msg.workSourceUid = ThreadLocalWorkSource.getUid();
if (mAsynchronous) {
//设置为异步方法
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
...enqueueMessage(...):精简了一些代码,完整代码,可点击左侧方法名
A,B,C消息依次发送,三者分边延时:3秒,1秒,2秒 { A(3000)、B(1000)、C(2000) }
这是一种理想情况:三者依次进入,进入之间的时间差小到忽略,这是为了方便演示和说明
这种按照时间远近的循序排列,可以保证未延时或者延时时间较小的消息,能够被及时执行
在消息队列中的排列为:B ---> C ---> A
mMessage为空,传入的msg则为消息链表头,next置空
mMessage不为空、消息队列中没有延时消息的情况:从当前分发位置移到链表尾,将传入的msg插到链表尾部,next置空
Message通过enqueueMessage加入消息队列
请明确:when = SystemClock.uptimeMillis() + delayMillis,when代表的是一个时间刻度,消息进入到消息队列,是按照时间刻度排列的,时间刻度按照从小到大排列,也就是说消息在消息队列中:按照从现在到未来的循序排队
这地方有几种情况,记录下:mMessage为当前消息分发到的消息位置
mMessage不为空、含有延时消息的情况:举个例子
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;
}
...来看下发送的消息插入消息队列的图示

接受消息相对而言就简单多
dispatchMessage(msg):关键方法呀
Handler.java
...
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
...handleCallback(msg)
触发条件:Message消息中实现了handleCallback回调
现在基本上只能使用post()方法了,setCallback(Runnable r) 被表明为@UnsupportedAppUsage,被hide了,没法调用,如果使用反射倒是可以调用,但是没必要。。。
mCallback.handleMessage(msg)
使用sendMessage方法发送消息(必须)
实现Handler的Callback回调
触发条件
分发的消息,会在Handler中实现的回调中分发
handleMessage(msg)
使用sendMessage方法发送消息(必须)
未实现Handler的Callback回调
实现了Handler的Callback回调,返回值为false(mCallback.handleMessage(msg))
触发条件
需要重写Handler类的handlerMessage方法
消息分发是在loop()中完成的,来看看loop()这个重要的方法
Looper.loop():精简了巨量源码,详细的可以点击左侧方法名
Message msg = queue.next():遍历消息
msg.target.dispatchMessage(msg):分发消息
msg.recycleUnchecked():消息回收,进入消息池
Looper.java
...
public static void loop() {
final Looper me = myLooper();
...
final MessageQueue queue = me.mQueue;
...
for (;;) {
//遍历消息池,获取下一可用消息
Message msg = queue.next(); // might block
...
try {
//分发消息
msg.target.dispatchMessage(msg);
...
} catch (Exception exception) {
...
} finally {
...
}
....
//回收消息,进图消息池
msg.recycleUnchecked();
}
}
...遍历消息的关键方法肯定是下面这个
Message msg = queue.next():Message类中的next()方法;当然这必须要配合外层for(无限循环)来使用,才能遍历消息队列
来看看这个Message中的next()方法吧
next():精简了一些源码,完整的点击左侧方法名
MessageQueue.java
...
Message next() {
final long ptr = mPtr;
...
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
...
//阻塞,除非到了超时时间或者唤醒
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;
// 这是关于同步屏障(SyncBarrier)的知识,放在同步屏障栏目讲
if (msg != null && msg.target == null) {
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//每个消息处理有耗时时间,之间存在一个时间间隔(when是将要执行的时间点)。
//如果当前时刻还没到执行时刻(when),计算时间差值,传入nativePollOnce定义唤醒阻塞的时间
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
mBlocked = false;
//该操作是把异步消息单独从消息队列里面提出来,然后返回,返回之后,该异步消息就从消息队列里面剔除了
//mMessage仍处于未分发的同步消息位置
if (prevMsg != null) {
prevMsg.next = msg.next;
} else {
mMessages = msg.next;
}
msg.next = null;
if (DEBUG) Log.v(TAG, "Returning message: " + msg);
msg.markInUse();
//返回符合条件的Message
return msg;
}
} else {
// No more messages.
nextPollTimeoutMillis = -1;
}
//这是处理调用IdleHandler的操作,有几个条件
//1、当前消息队列为空(mMessages == null)
//2、已经到了可以分发下一消息的时刻(now < mMessages.when)
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);
}
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;
}
}总结下源码里面表达的意思
next()内部是个死循环,你可能会疑惑,只是拿下一节点的消息,为啥要死循环?
为了执行延时消息以及同步屏障等等,这个死循环是必要的
nativePollOnce阻塞方法:到了超时时间(nextPollTimeoutMillis)或者通过唤醒方式(nativeWake),会解除阻塞状态
nextPollTimeoutMillis大于等于零,会规定在此段时间内休眠,然后唤醒
消息队列为空时,nextPollTimeoutMillis为-1,进入阻塞;重新有消息进入队列,插入头结点的时候会触发nativeWake唤醒方法
如果 msg.target == null为零,会进入同步屏障状态
会将msg消息死循环到末尾节点,除非碰到异步方法
如果碰到同步屏障消息,理论上会一直死循环上面操作,并不会返回消息,除非,同步屏障消息被移除消息队列
当前时刻和返回消息的when判定
消息when代表的时刻:一般都是发送消息的时刻,如果是延时消息,就是 发送时刻+延时时间
当前时刻小于返回消息的when:进入阻塞,计算时间差,给nativePollOnce设置超时时间,超时时间一到,解除阻塞,重新循环取消息
当前时刻大于返回消息的when:获取可用消息返回
消息返回后,会将mMessage赋值为返回消息的下一节点(只针对不涉及同步屏障的同步消息)
这里简单的画了个流程图

分发消息主要的代码是: msg.target.dispatchMessage(msg);
也就是说这是Handler类中的dispatchMessage(msg)方法
dispatchMessage(msg)
public void dispatchMessage(@NonNull Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}可以看到,这里的代码,在收发消息栏目的接受消息那块已经说明过了,这里就无须重复了
msg.recycleUnchecked()是处理完成分发的消息,完成分发的消息并不会被回收掉,而是会进入消息池,等待被复用
recycleUnchecked():回收消息的代码还是蛮简单的,来分析下
默认最大容量为50: MAX_POOL_SIZE = 50
首先会将当前已经分发处理的消息,相关属性全部重置,flags也标志可用
消息池的头结点会赋值为当前回收消息的下一节点,当前消息成为消息池头结点
简言之:回收消息插入消息池,当做头结点
需要注意的是:消息池有最大的容量,如果消息池大于等于默认设置的最大容量,将不再接受回收消息入池
Message.java
...
void recycleUnchecked() {
// Mark the message as in use while it remains in the recycled object pool.
// Clear out all other details.
flags = FLAG_IN_USE;
what = 0;
arg1 = 0;
arg2 = 0;
obj = null;
replyTo = null;
sendingUid = UID_NONE;
workSourceUid = UID_NONE;
when = 0;
target = null;
callback = null;
data = null;
synchronized (sPoolSync) {
if (sPoolSize < MAX_POOL_SIZE) {
next = sPool;
sPool = this;
sPoolSize++;
}
}
}来看下消息池回收消息图示

既然有将已使用的消息回收到消息池的操作,那肯定有获取消息池里面消息的方法了
obtain():代码很少,来看看
如果消息池不为空:直接取消息池的头结点,被取走头结点的下一节点成为消息池的头结点
如果消息池为空:直接返回新的Message实例
Message.java
...
public static Message obtain() {
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
return new Message();
}来看下从消息池取一个消息的图示

在MessageQueue类中的next方法里,可以发现有关于对IdleHandler的处理,大家可千万别以为它是什么Handler特殊形式之类,这玩意就是一个interface,里面抽象了一个方法,结构非常的简单
next():精简了大量源码,只保留IdleHandler处理的相关逻辑;完整的点击左侧方法名
MessageQueue.java
...
Message next() {
final long ptr = mPtr;
...
int pendingIdleHandlerCount = -1; // -1 only during first iteration
int nextPollTimeoutMillis = 0;
for (;;) {
...
//阻塞,除非到了超时时间或者唤醒
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;
...
//这是处理调用IdleHandler的操作,有几个条件
//1、当前消息队列为空(mMessages == null)
//2、未到到了可以分发下一消息的时刻(now < mMessages.when)
//3、pendingIdleHandlerCount < 0表明:只会在此for循环里执行一次处理IdleHandler操作
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
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);
}
}
}
pendingIdleHandlerCount = 0;
nextPollTimeoutMillis = 0;
}
}实际上从上面的代码里面,可以分析出很多信息
IdleHandler相关信息
调用条件
当前消息队列为空(mMessages == null) 或 未到分发返回消息的时刻
在每次获取可用消息的死循环中,IdleHandler只会被处理一次:处理一次后pendingIdleHandlerCount为0,其循环不可再被执行
实现了IdleHandler中的queueIdle方法
返回false,执行后,IdleHandler将会从IdleHandler列表中移除,只能执行一次:默认false
返回true,每次分发返回消息的时候,都有机会被执行:处于保活状态
IdleHandler代码
MessageQueue.java
...
/**
* Callback interface for discovering when a thread is going to block
* waiting for more messages.
*/
public static interface IdleHandler {
/**
* Called when the message queue has run out of messages and will now
* wait for more. Return true to keep your idle handler active, false
* to have it removed. This may be called if there are still messages
* pending in the queue, but they are all scheduled to be dispatched
* after the current time.
*/
boolean queueIdle();
}
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
public void removeIdleHandler(@NonNull IdleHandler handler) {
synchronized (this) {
mIdleHandlers.remove(handler);
}
}怎么使用IdleHandler呢?
public class MainActivity extends AppCompatActivity {
private TextView msgTv;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgTv = findViewById(R.id.tv_msg);
//添加IdleHandler实现类
mHandler.getLooper().getQueue().addIdleHandler(new InfoIdleHandler("我是IdleHandler"));
mHandler.getLooper().getQueue().addIdleHandler(new InfoIdleHandler("我是大帅比"));
//消息收发一体
new Thread(new Runnable() {
@Override public void run() {
String info = "第一种方式";
mHandler.post(new Runnable() {
@Override public void run() {
msgTv.setText(info);
}
});
}
}).start();
}
//实现IdleHandler类
class InfoIdleHandler implements MessageQueue.IdleHandler {
private String msg;
InfoIdleHandler(String msg) {
this.msg = msg;
}
@Override
public boolean queueIdle() {
msgTv.setText(msg);
return false;
}
}
}这里简单写下用法,可以看看,留个印象
通俗的讲:当所有消息处理完了 或者 你发送了延迟消息,在这俩种空闲时间里,都满足执行IdleHandler的条件