1.Demo
package com.jzzh.handlertest;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
/**
* 为什么只能在主线程中更新UI,因为每次更新都会去判断当前线程是不是主线程,如果不是就抛出异常
* 把抛出异常的代码注释调,就可以在子线程中更新UI了,为什么android要这样做呢,大概是为了避免
* 由于多个线程去更新UI而导致出现其他问题(UI错乱等),索性作出一个规定,让开发者按照规定去做从而可以避免一些问题
* */
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.handler_text);
MyThread t = new MyThread("sub");//创建一个名字为sub的子线程
t.start();
//new Thread(r3).start();//并不是实现Runnable就创建线程,使用Runnable只是把Thread的run方法的内容搬到Runnable中去,通过这种方式解耦
}
Handler mMainHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
return false;//返回false下面的handleMessage没被拦截,会继续执行,返回true则会被拦截
}
}){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
mTextView.setText("xml");
}
};
private class MyThread extends Thread{
public MyThread(@NonNull String name) {
super(name);
}
Handler handler = new Handler();//它不是子线程中的Handler,要在run()方法中new的Handler才是子线程中创建Handler
public void run() {
super.run();
Log.v("xml_log_test","MyThread----------"+Thread.currentThread().getName());
try {
sleep(1000);//如果不休眠下面的更新UI不会报错
} catch (Exception e){
}
//mTextView.setText("xml");
Looper.prepare();//没它new Handler会报错
Handler mSubHandler = new Handler();//它是子线程中的Handle
//这两行代码只是做实验证明Runnable中的run方法所在线程跟在哪里创建无关,跟Handler有关
mMainHandler.post(newInSubRunnable);//虽然newInSubRunnable在MyThread中创建,但是由于他的Handler是主线程中创建的的,他的run方法会在主线中执行
mSubHandler.post(newInSubRunnable);//mSubHandler是子线程中的Handler,此时newInSubRunnable的run方法会在子线中执行,此时不能在里面更新UI
//以下是更新UI的几种方式
//updateUiFun1();
//updateUiFun2();
//updateUiFun3();
updateUiFun4();
Looper.loop();//没它子线程中的消息不会被发送
}
private void updateUiFun1() {
mMainHandler.post(newInMainRunnable);
}
private void updateUiFun2() {
mMainHandler.sendEmptyMessage(1);
}
private void updateUiFun3() {
mTextView.post(newInMainRunnable);
}
private void updateUiFun4() {
runOnUiThread(newInMainRunnable);
}
private Runnable newInSubRunnable = new Runnable() {
@Override
public void run() {
Log.v("xml_log_test","newInSubRunnable----------"+Thread.currentThread().getName());
}
};
}
private Runnable newInMainRunnable = new Runnable() {
@Override
public void run() {
Log.v("xml_log_test","newInMainRunnable----------"+Thread.currentThread().getName());
mTextView.setText("xml");
}
};
}
整个Activity类贴出来,布局文件只有一个简单TextView
2.带着问题出发
1.如何在子线程中利用Handler去更新UI?
2.Handler、Looper,MessageQueue的关系?
3.android中为什么一定要在主线程中更新UI?
4.在onCreate方法中,如果创建的子线程不休眠,为什么可以更新UI?
3.分析问题
1.如何在子线程中利用Handler去更新UI?
如Demo中的updateUiFun1(),updateUiFun2(),updateUiFun3(),updateUiFun4()用法
2.Handler、Looper,MessageQueue的关系?
在子线程中创建一个Handler发送消息的流程分4步:Looper.prepare() ---> Handler mSubHandler = new Handler() ---> mSubHandler.post(newInSubRunnable) ---> Looper.loop(),分析其中的源码从Looper.prepare()开始,可以看到带Demo中这行代码有一个注释没它new Handler会报错,这是为什么呢,带着这个问题开始出发
frameworks/base/core/java/android/os/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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
Looper.prepare()会直接调用一个重载方法,在重载方法中把新建的Looper对象保存到了sThreadLocal中去,ThreadLocal称之为本地线程变量,是用来保存当前线程中一些数据,在prepare(boolean)中可以看出来,每一个线程只能有一个Looper对象,不然会抛出RuntimeException("Only one Looper may be created per thread")异常,在new Looper中又创建了MessageQueue对象mQueue。Looper.prepare() 分析完毕,接着看Handler mSubHandler = new Handler()的源码
frameworks/base/core/java/android/os/Handler.java
public Handler(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 that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
frameworks/base/core/java/android/os/Looper.java
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
在new Handler的时候获取Looper对象是用Looper.myLooper(),再看看Looper.myLooper(),返回的是本地线程变量sThreadLocal取出来的Looper,那如果前面没有进行Looper.prepare()的话,调用Looper.myLooper()得到的就是空,所以到这里就可以解答为什么不调Looper.prepare()就会报RuntimeException("Can't create handler inside thread that has not called Looper.prepare()")异常了。除此之外还从mLooper中取得MessageQueue对象,前面说过MessageQueue是在创建Looper对象时创建的。如果new Handler的时候有传Callback参数,则把它存在mCallback中。接着分析下一步Handler的post系列跟sendMessage系列方法
frameworks/base/core/java/android/os/Handler.java
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
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) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
sendMessage跟post方法都是都是调用sendMessageDelayed,唯一不同的是post方法,把传进来的Runnable封装到Message中去,而sendMessage传过来直接就是Message不需要进行其他操作。接着调用sendMessageAtTime,在sendMessageAtTime中再enqueueMessage(queue, msg, uptimeMillis),在enqueueMessage方法中msg.target = this这句留意一下,他是把Handler自己保存到Message的target中去。再把Message放入到MessageQueue队列中。放入队列中,却还没有发送出去,再调用Looper.loop(),看看是怎么把消息发送出去的
frameworks/base/core/java/android/os/Looper.java
public static void loop() {
final Looper me = myLooper(); //从本地线程变量sThreadLocal中获取Looper对象
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;//从Looper对象中获取MessageQueue对象
// 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(); // 不断在MessageQueue取出Message,可能会阻塞
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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
final long end;
try {
msg.target.dispatchMessage(msg); //再调用Handler的dispatchMessage方法
end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (slowDispatchThresholdMs > 0) {
final long time = end - start;
if (time > slowDispatchThresholdMs) {
Slog.w(TAG, "Dispatch took " + time + "ms on "
+ Thread.currentThread().getName() + ", h=" +
msg.target + " cb=" + msg.callback + " msg=" + msg.what);
}
}
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();
}
}
在Looper.loop()方法中先获取Looper对象,再通过Looper获取MessageQueue,然后开起死循环,不断从MessageQueue取出Message,然后再调用msg.target的dispatchMessage方法,前面说过msg.target就是Handler他自己,所以这里就是调用Handler的dispatchMessage方法
frameworks/base/core/java/android/os/Handler.java
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
最后来到Handler的dispatchMessage方法,在这之中首先判断msg.callback是否为空,但是我们前面分析的过程貌似没有对msg.callback进行过赋值,所以直接看else,前面说过,在new Handler的时候,如果有传Callback进来,时会保存到mCallback中去的,如果有Callback旧会先调用Callback的handleMessage方法,如果Callback的handleMessage方法返回true则直接return了,不会再继续执行Handler的handleMessage方法,这个代码就解释了Demo中第35行中注释的原因
通过上面的代码分析,在总结一下问题2:Handler、Looper,MessageQueue的关系?
答:Handler把Message放到MessageQueue中,Looper再从MessageQueue拿出Message,然后再把他发回给Handler
Handler:发信人,收信人
Message:信封(内容就是Messag.arg1,Messag.target等这些)
MessageQueue:邮箱,用于存放信封的
Looper:邮递员,不断从信箱中拿出信封,然后在给收信人
3.android中为什么一定要在主线程中更新UI?
frameworks/base/core/java/android/view/ViewRootImpl.java
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
在UI更新的时候时ViewRootImpl会去检查线程,判断当前线程是不是主线程,如果就会抛出异常,如果把异常注释调,发现依然可以在子线程中更新UI。android为什么要限制开发者不要在其他线程中更新UI呢,可能由于多线程的不同步可呢个会导致UI的错乱,但是如果同步了,又会影响效率。索性旧统一在一个线程(主线程,UI线程)中更新UI了
4.在onCreate方法中,如果创建的子线程不休眠,为什么可以更新UI?
在Demo中代码56行与60行,如果把56行sleep(1000)注释掉,60行mTextView.setText("xml")代码打开,发现可以在子线程中更新UI,这是怎么回事呢?原因在于ViewRootImp是在onResume()创建的,在onCreate中没有进行问题3中的线程判断。但是如果休眠了一段时间,onResume()已经被回调,那么ViewRootImp就被创建了,这么一来,此时再子线程中更新UI,就会去判断是否是主线程,从而抛出异常
5.补充:为什么在主线成中没有Looper.myLooper()跟Looper.loop(),Handler却能正常使用呢?
frameworks/base/core/java/android/app/ActivityThread.java
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
// CloseGuard defaults to true and can be quite spammy. We
// disable it here, but selectively enable it later (via
// StrictMode) on debug builds, but using DropBox, not logs.
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();//<------------------------------1
ActivityThread thread = new ActivityThread();
thread.attach(false);//<-------------------------------2
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();//<------------------------------3
throw new RuntimeException("Main thread loop unexpectedly exited");
}
activity的主线程ActivityThread的mian方法中代码中标记的1和3完成Looper.myLooper()跟Looper.loop(),而我们自己创建的Handler其实就是在2的过程中