看了网上的一些handler原理分析,是从源码级别直接看的。但是总觉得没有从实战上分析吗,感觉有点蹩脚。这篇文章算是自己分析的,也参考了《android开发艺术探索》,还有网上的一些其他资料,如有侵权请私信
先来举个栗子吧
一般在使用handler的时候,用其来更新UI,也就是说在主线程进行更新界面操作,当时子线程请求网络数据,如此handler刚好派上用场。先看实例吧
public class MainActivity extends Activity {
private TextView text;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
text.setText("使用Handler更新了界面");
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.id_text);
new Thread("#Thread1") {
@Override
public void run() {
//...你的业务逻辑;
Message message = new Message();//发送一个消息,该消息用于在handleMessage中区分是谁发过来的消息;
message.what = 1;
handler.sendMessage(message);
}
}.start();
}
}
以上的例子呢,应该算是handler使用的最普遍的,当然还有其它用法,handler创建在主线程中,也就是Activitythread,在"#Thread1"中执行耗时操作,在主线程中更新UI,创建handler。
在创建handler之前需要注意:
在创建handler之前,必须先在相同线程内创建一个Looper,每个线程中最多只能有一个 Looper 对象,由 Looper 来管理此线程里的 MessageQueue (消息队列)。
如果不在主线程创建handler的话,应该这么写代码:
new Thread("Thread#2"){
@override
public void run(){
Looper.prepare();
Handler handler = new Handler();
Looper.loop();
}
}
首先利用Looper.prepare()创建looper,然后创建handler,然后调用Looper.loop()开启消息循环。这是在非UI线程,但是我们在之前的handler使用例子中并未简单looper的创建啊,其实looper 已经在activityThread当中给你创建完了。可以来看看源码
public static void main(String[] args) {
、、、、、此处省略部分代码
Process.setArgV0("<pre-initialized>");
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
thread.attach(false);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
AsyncTask.init();
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
可以看出activitythread执行了两个looper方法
Looper.prepareMainLooper();
Looper.loop();
所以我们只需要创建handler就可以了。那我们接着看我们文章开头那个实例,重写了handler的handlemessage方法,然后新建线程,利用handler发送消息。然后主线程的handler就会接收到消息,并在handlemessage中处理消息。上面整体思路没问题吧,这也是最初在使用handler的时候,大家的通常思维,那handler到底是怎么切换线程的,从thread1切换到了主线程???
先上一张整体的流程图
这张图是我自己画的,可能画的不太好,也看了一些大佬的流程图,毕竟我基础差,总觉得他们的图理解起来不是很容易。
MessaggeQueue类详解
根据我们的操作先来看啊,主线程已经准备就绪,handler创建完了,然后调用sendmessage方法,最后调用的事enqueuemessage()方法,然后就到了messgaeQueue类,这个类又是从哪来的呢????这个类其实是从Looper里面蹦出来的,在创建Looper的时候,就会生成MessageQueue,来看一下源码
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));
}
/**
* Initialize the current thread as a looper, marking it as an
* application's main looper. The main looper for your application
* is created by the Android environment, so you should never need
* to call this function yourself. See also: {@link #prepare()}
*/
public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}
我们知道在主线程的main函数中,已经调用了prepareMainLooper()方法,而后prepareMainLooper()方法又调用了 prepare()方法,在这个方法里面,我们调用looper的构造函数,并将新建的looper存入到了ThreadLocal里面(ThreadLocal后边讲),然后我们来看这个looper的构造函数
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}
可以清晰的看到Looper在构造函数中创建了MessageQueue,知道了MessageQueue的由来,我们简单来说一下MessageQueue这个类啊
enqueueMessage():这个是通过维护一个单链表,handler添加消息以后,MessageQueue会将消息添加到最后。
next():用于取出消息,并将消息传递给Looper 。注意这个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;
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 (false) Log.v("MessageQueue", "Returning message: " + msg);
return msg;
}
} else {
// No more messages.
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("MessageQueue", "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;
}
}
Looper类详解
我们这时候来看看looper,looper是在主线程的,刚刚说过了,looper在handler创建之前就已经创建完成了,顺带把MessageQueue和looper.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.");
}
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();
for (;;) {
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
Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(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();
}
}
和上面next方法一样,这块也是个死循环,一直在等待messagequeue的消息。等它拿到消息以后,就会调用msg.target.dispatchMessage(msg);这行代码,这行代码其实就是调用了handler的dispatchMessage方法,后边经过一些列的判断会调用handler的handleMessage()方法。这是整体过程。
总结
下面从别的文章上抄来的图,简单粗暴。很明显就能看出如何切换线程的,首先主线程就相当于A线程,B线程就相当于#Thread1
POST就相当于在thread1里面使用handler发送消息,然后把消息放在messageQueue当中,主线程里面的Looper就回调用loop方法,一直从messagequeue类的next方法中获取消息,然后再次调用handler消化这个消息。
引用的技术文章
https://blog.csdn.net/AdobeSolo/article/details/75195394
https://mp.weixin.qq.com/s/D1v7b5CUT-3JMhxR6iCpcA
https://blog.csdn.net/CHENYUFENG1991/article/details/46910675
《android开发艺术探索》
网友评论