前言:奋斗是这么个过程,当时不觉累,事后不会悔。走一段再回头,会发现一个更强的自己,宛如新生!
一、概述
在Android开发过程中,我们常常会将一些耗时的操作放在子线程中执行(work thread),然后将执行的结果告诉UI线程(main thread)也叫主线程,因为UI的更新只能在Main Thread中执行,那么这里就涉及怎么将数据传递给主线程(main thread),需要借助安卓的消息机制。
Android为我们提供了消息传递机制——Handler,来帮助我们将数据从子线程传递给主线程,其实,当我们熟悉Handler的原理之后,Handler不仅能实现子线程传递数据给主线程,还能实现任意两个线程之间的数据传递。
主线程:也叫UI线程,或者Activity Thread,用于运行四大组件和用户的交互,用于处理各种和界面相关的事情,Activity Thread管理应用进程的主线程的执行。
子线程:用于执行耗时操作,比如I/O操作或者网络请求,安卓3.0以后要求访问网络必须在子线程中执行,更新UI的操作必须交给主线程,子线程不允许更新UI。
1.什么是消息机制?
不同线程之间的通信。
2.什么是安卓消息机制?
Handler运行机制。
3.安卓消息机制有什么用?
线程之间通信,主要是避免ANR(Application Not Responding),一旦出现ANR,程序就会崩溃。
4.什么情况下出现ANR?
- Activity里面的响应超过5秒;
- Broadcast在处理的时间超过10秒;
- Service处理时间超过20秒;
造成上面三种情况的原因很多,网络请求,大文件的读取,耗时的计算等都会引发ANR。
5.如何避免ANR?
主线程不能执行耗时操作,子线程不行更新UI,那么把耗时操作放到子线程中执行,通过Handler消息机制通知主线程更新UI。
6.为什么子线程不能更新UI?
在Andorid系统中出于性能优化的考虑,UI操作不是线程安全的,这意味着多个线程并发操作ui控件可能会导致线程安全问题,如果对UI控件加上上锁机制,会使控件变得复杂低效,也会阻塞某些进程的执行。为了解决这个问题,Android规定只允许UI线程(主线程)修改Activity中的UI组件,但是实际上,有部分UI需要在子线程中控制逻辑,因此子线程需要通过Handler通知主线程修改UI,实现线程间通信。最根本就是为了解决多线程并发的问题。
二、Handler的使用
首先来看下Handler最常规的使用模式(源码地址在文章最后给出)
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
mTextView.setText((String) msg.obj);
Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
break;
}
}
};
/**
* 子线程通知主线程更新UI
*/
private void sendMsgToMainThreadByWorkThread() {
//创建子线程
new Thread(new Runnable() {
@Override
public void run() {
//获取消息载体
Message msg = Message.obtain();
msg.what = 1;
msg.obj = "子线程通知主线程更新UI";
mHandler.sendMessage(msg);
}
}).start();
}
通常我们在主线程中创建一个Handler,通过重写handler的handleMessage(Message msg)方法,从参数Message中获取传递过来的信息数据,子线程中通过obtain()获取Message信息载体实例,最后通过sendMessage(msg)发送消息,我们来看看Message的几个属性:
- Message.what 用来标识信息得int值,区分来自不同地方的信息来源
- Message.obj 用来传递的实例化对象(信息数据)
- Message.arg1/Message.arg2 Message初始定义的用来传递int类型值的两个变量
Handler消息机制的处理过程:从Handler中通过obtainMessage()获取消息对象Message,把数据封装到Message消息对象中,通过handler的sendMessage()方法把消息push到MessageQueque中,Looper对象会轮询MessageQueque队列,把消息对象取出,再通过dispatchMessage分发给handler,通过回调实现handler的handleMessage方法处理消息。
这里引出了handler机制的几个关键对象,handler、Looper、MessageQueque、Message。
Handler:发送和处理消息,它把消息发送给Looper管理的MessageQueque,并负责处理Looper发送给他的消息
Looper:消息队列的处理者(轮询队列),每个线程只有一个Looper,负责管理MessageQueque,会不断地从Message中取出消息,分发给Handler
Message:消息对象(存储数据),它封装了任务携带的额外信息和处理该任务的 Handler 引用。
MessageQueque:消息队列,由Looper管理,采用先进先出的方法管理Message(存放数据结构,内部使用链表数据结构存储多个消息对象,最大长度为50,目的是为了重用message对象,减少Message对象的创建,造成产生大量的垃圾对象)
三、任意线程和原理
我们来看看任意两个子线程间调用handler:
private Handler handler;
/**
* 任意线程间的通信
*/
private void handlerWorkThread() {
new Thread(new Runnable() {
@Override
public void run() {
// Looper.prepare();//不写此代码会报异常
// 注意:一定要在两个方法之间创建绑定当前Looper的Handler对象,
// 否则一旦线程开始进入死循环就没法再创建Handler处理Message了
handler = new Handler() {
@Override
public void handleMessage(final Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 2:
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.setText((String) msg.obj);
Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
System.out.println("Str=============================" + msg.obj);
}
});
break;
}
}
};
//开始循坏处理消息队列
// Looper.loop();//不写此代码会无法接受数据
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//不需要直接new Message,通过handler.obtainMessage()获取Message实例,底层直接是
//调用了Message.obtain()方法,实现消息的复用,Message内部维护有数据缓存池
Message message = handler.obtainMessage();
message.what = 2;
message.obj = "任意线程间的通信";
handler.sendMessage(message);
}
}).start();
}
从代码中,我们创建了两个子线程,在第一个子线程中创建handler,并且实现handlerMessage()方法,在第二个子线程中创建消息实例Message,封装数据并通过handler发送。将上面的代码跑起来,但是报异常了:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
No Looper;
注意:一个线程创建handler时是需要先创建Looper的,而且每个线程只需要创建一个Looper,否则会报错:
RuntimeException: Only one Looper may be created per thread。
其实,子线程中如果使用handler需要手动调用Looper.prepare()和Looper.loop(),不调用Looper.prepare()会报上面两个异常,不调用Looper.loop()则会handler收不到消息,我们来看看为什么子线程中不创建Looper会报错,在new Handler()为什么会报错,
3.1 Handler
//可以看到Looper为空的时候才跑出该异常
public Handler(Callback callback, boolean async) {
//关联到当前线程的Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
//持有当前Looper中消息队列的引用
mQueue = mLooper.mQueue;
mCallback = callback;
//设置消息是否异步
mAsynchronous = async;
}
//我们来看看Looper.prepare()都干了什么
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));
}
//可以看出在当前Thread创建了一个Looper,ThreadLocal主要用于维护本地线程的变量,而Looper的构造函
//数又为我们创建了一个消息队列MessageQueue
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
但是为什么主线程中不需要Looper.prepare()和Looper.loop(),其实是因为App初始化的时候都会执行ActivityThread的main方法,所以UI线程能直接使用Handler,我们可看一看里面做了什么操作:
3.2 ActivityThread-Main
public static void main(String[] args) {
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");
}
从中可以看到在创建主线程的时候android已经帮我们调用了Looper.prepareMainLooper()和Looper.loop()方法,所以我们能再主线程中直接创建Handler使用。
我们来看看Handler发送消息的过程,有多个方法实现这个功能,如:post()、postAtTime()、postDelayed()、sendMessage()、sendMessageAtTime()、sendMessageDelayed()等等:
3.3 handler发送消息
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
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);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
// 核心代码,sendMessage一路调用到此,让Message持有当前Handler的引用
// 当消息被Looper线程轮询到时,可以通过target回调Handler的handleMessage方法
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
//将message加入MessageQueque中,并且根据消息延迟排序
return queue.enqueueMessage(msg, uptimeMillis);
}
最后一段是发送消息的核心代码,handler发送消息最终会走到这里,让Message持有当前Handler的引用,当消息被Looper轮询到时,可以通过target回调handler的handleMessage()方法,sendMessage()的关键在于queue.enqueueMessage(msg, uptimeMillis),其内部调用了MessageQueque的enqueueMessage()方法。
3.4 MessageQueque
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) {
//队列无消息或者插入消息的执行时间为0(强制插入队头)亦或者插入消息的执行时间先于队头时间,这三总情况插入消息为新队头,如果队列被阻塞,则会被唤醒。
// 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;
}
从代码可以看出,Message存放到MessageQueque中时,是将Message存放到Message.next中,形成一个链式的列表,同时也保证了Message列表的时序性,MessageQueque.next()方法从消息队列中取出一个需要处理的消息,如果没有消息或者消息还没到时该队列会阻塞,等待消息通过MessageQueque.enqueueMessage()进入消息队列后唤醒线程。
MessageQueque.next()
Message next() {
······
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();
}
//通过Native层的MessageQueque阻塞nextPollTimeoutMillis毫秒时间
nativePollOnce(ptr, nextPollTimeoutMillis);
synchronized (this) {
//尝试检索下一条消息,如果找到则返回该消息
final long now = SystemClock.uptimeMillis();
Message prevMsg = null;
Message msg = mMessages;
if (msg != null && msg.target == null) {
//被target为null的消息屏障阻塞,查找队列中的下一个异步消息
do {
prevMsg = msg;
msg = msg.next;
} while (msg != null && !msg.isAsynchronous());
}
if (msg != null) {
if (now < msg.when) {
//下一个消息尚未就绪,设置超时以在准备就绪时唤醒
nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
} else {
//从队列中获取一个重要执行的消息
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 {
//队列没有消息,一值被阻塞,等待唤醒
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;
}
}
Message的发送实际是放入Handler对应线程的MessageQueque中,那么Message是如何被取出来的呢?在前面的例子也讲到,如果不调用Looper.loop()的话,handler是接收不到消息的,我们来看看loop()方法:
3.5 Looper
Looper.loop()
/**
* Run the message queue in this thread. Be sure to call
* {@link #quit()} to end the loop.
*/
public static void loop() {
//得到当前线程的Looper对象
final Looper me = myLooper();
//调用Looper.prepare()之前是不能调用该方法的,不然又抛异常了
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//等到消息队列
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,该方法可以被阻塞
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// 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);
}
······
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
//将message推送到Message中的target处理,此处的target就是发送该Message的handler对象
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
·······
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
·······
//回收message,这样通过Message.obtain()复用
msg.recycleUnchecked();
}
}
该方法启动线程的循环模式,从Looper的MessageQueque中不断提取Message,再交给Handler处理任务,最后回收Message复用。我们再回头看下Looper.prepare()方法:
Looper.prepare()
public final class Looper {
//每个线程仅包含一个Looper对象,定义为一个本地存储对象
static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
private static Looper sMainLooper; // guarded by Looper.class
//每一个Looper维护一个唯一的消息队列
final MessageQueue mQueue;
final Thread mThread;
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
public static void prepare() {
prepare(true);
}
//该方法会在调用线程的TLS中创建Looper对象,为线程私有
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
//如果Looper已经存在则抛出异常
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
}
该方法在线程中将Looper定义为ThreadLocal对象,使得Looper成为线程的私有对象,一个线程最多仅有一个Looper,并在这Looper对象中维护一个消息队列MessageQueque和持有当前线程的引用,因此MessageQueque也是线程私有。
从上面的Looper.loop()中得知,Looper通过MessageQueque中取出消息Message,通过Message的Target(就是handler)调用dispatchMessage()去分发消息,继续分析Message的分发:
3.6 handler-handleMessage()
public interface Callback {
public boolean handleMessage(Message msg);
}
/**
* Handle system messages here.
*/
//处理消息,此方法由Looper的loop方法调用
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
//处理Runnable类消息
handleCallback(msg);
} else {
//这种方法允许Activity等实现Handler.Callback接口,避免自己定义handler重写HandleMessage()方法
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
//根据handler子类实现回调方法处理消息
handleMessage(msg);
}
}
//处理Runnable类消息方法
private static void handleCallback(Message message) {
//直接调用Message中封装的Runnable的run方法
message.callback.run();
}
//handler子类实现回调的方法
public void handleMessage(Message msg) {
}
如果设置了callback(Runnable对象),则会直接调用handleCallback方法,如果msg.callback==null,会直接调用我们的mCallback.handleMessage(msg),即handler的handlerMessage方法。由于Handler对象是在主线程中创建的,所以handler的handlerMessage方法的执行也会在主线程中。
任何持有handler引用的其他线程都可发送消息,消息都发送到Handler内部关联的MessageQueque中,而handler是在Looper线程中创建的(Looper.praprepare()之后,Looper.loop()之前),所以handler是在其关联的Looper线程中处理取得关联消息的。
3.7 Message
在消息处理机制中,Message扮演的角色就是消息本身,它封装了任务携带的额外消息和处理该任务的Handler引用。
Message虽然有public构造方法,但是还是建议用Message.obtain()从一个全局的消息池中得到空的Message对象,这样有效的节省系统资源,Handler有一套obtain方法,其本质是调用Message的obtain方法,最终都是调用Message.obtain()。
另外可以利用Message.what来区分消息类型,以处理不同的任务,在需要携带简单的int类型额外消息时,可以优先使用Message.arg1和Message.arg2,这样比bundle封装消息更省资源。
源码总结:
1、创建Handler实例,关联Looper(非主线程还要调用looper.prepare(),handler所创建的线程需要维护一个唯一的Looper对象,一个线程最多仅有一个Looper,每个线程的Looper通过ThreadLocal来保证,并在这Looper对象中维护一个消息队列MessageQueque和持有当前线程的引用)。
2、Handler通过sendMessage(Message msg)发送消息,sendMessage()其内部最终调用了MessageQueque的enqueueMessage()方法。将message时序性放入Handler对应线程的MessageQueque中。Message在MessageQueue不是通过一个列表来存储的,而是将传入的Message存入到了上一个Message的next中,在取出的时候通过顶部的Message就能按放入的顺序依次取出Message
3、Looper.loop()启动线程的循环模式,从Looper的MessageQueque中不断提取Message,通过msg.target.dispatchMessage(msg)完成消息的发送,将message推送到Message中的target(handler)处理,再交给Handler处理任务,最后回收Message复用。
4、最后handler实现handlerMessage()方法接收处理数据。
图片流程:
四、handler的使用注意事项
4.1 注意内存泄漏
使用Handler是用来线程间通信的,所以新开的线程会持有Handler的引用,如果在Activity中创建Handler并且是非静态内部类的形式,就有可能导致内存泄漏。
1.因为非静态内部类会隐式持有外部类的引用,当其他线程持有该handler,如果线程没有被销毁,就会知道Activity一直被Handler持有引用而导致无法回收。
2.如果消息队列MessageQueque中还有没处理完的消息,Message中的target也是会持有Activity的引用,也会造成内存泄漏。
解决办法:使用静态内部类+弱引用
(1.)静态内部类不会持有有外部了的引用,当使用外部类相关操作时,可以通过弱引用回去相关数据
public static class ProtectHandler extends Handler {
private WeakReference<Activity> mActivity;
public ProtectHandler(Activity activity) {
mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Activity activity = mActivity.get();
if (activity != null && !activity.isFinishing()) {
//todo
}
}
}
(2.)在外部类被销毁时,将消息队列清空,例如:在activity销毁时清空MessageQueque.
@Override
protected void onDestroy() {
//清空消息
mHandler.removeCallbacksAndMessages(null);
super.onDestroy();
}
4.2 ThreadLocal是什么?
ThreadLocal可以包装一个对象,使其成为线程私有的局部变量,通过ThreadLocal的get()和set()获得的变量,不受其他线程影响。ThreadLocal实现了线程之间的数据隔离,同时提升了同一线程访问变量的便利性。
至此,本文结束!
源码地址:https://github.com/FollowExcellence/HandlerDemo
请尊重原创者版权,转载请标明出处:https://blog.csdn.net/m0_37796683/article/details/100524852 谢谢!