Android面试常客之Handler全解2

简介: Android面试常客之Handler全解

接上一篇

Handler的sendMessage方法都做了什么

  还记得文章开始时的两个问题吗?

  • Handler明明是在子线程中发的消息怎么会跑到主线程中了呢?
  • Handler的发送消息handleMessage又是怎么接收到的呢?

下面就分析一下Handler的sendMessage方法都做了什么,看代码

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);
    }
/**
     * Enqueue a message into the message queue after all pending messages
     * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
     * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
     * Time spent in deep sleep will add an additional delay to execution.
     * You will receive it in {@link #handleMessage}, in the thread attached
     * to this handler.
     * 
     * @param uptimeMillis The absolute time at which the message should be
     *         delivered, using the
     *         {@link android.os.SystemClock#uptimeMillis} time-base.
     *         
     * @return Returns true if the message was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the message will be processed -- if
     *         the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     */
    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);
    }

由上面的代码可以看出,Handler的sendMessage方法最后调用了sendMessageAtTime这个方法,其实,无论时sendMessage、sendEmptyMessage等方法最终都是调用sendMessageAtTime。可以看到sendMessageAtTime这个方法最后返回的是*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);
    }

这里有一句代码非常重要,

 msg.target = this;

这句代码就是将当前的Handler赋值给了Message中的target变量。这样,就将每个调用sendMessage方法的Handler与Message进行了绑定。

enqueueMessage方法最后返回的是**queue.enqueueMessage(msg, uptimeMillis);**也就是调用了MessageQueue中的enqueueMessage方法,下面看下MessageQueue中的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) {
                // 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;
    }

上面的代码就是将消息放进消息队列中,如果消息已成功放入消息队列,则返回true。失败时返回false,而失败的原因通常是因为处理消息队列正在退出。代码分析到这里可以得出以下两点结论了

  1. Handler在sendMessage时会将自己设置给Message的target变量即将自己与发送的消息绑定。
  2. Handler的sendMessage是将Message放入MessageQueue中。

到了这里已经知道Handler的sendMessage是将消息放进MessageQueue中,那么又是怎样从MessageQueue中拿到消息的呢?想要知道答案请继续阅读。

怎样从MessageQueue中获取Message

  在文章的前面,贴出了ActivityThread类中的main方法的代码,不知道细心的你有没有注意到,在main方法的结尾处调用了一句代码

Looper.loop()

好了,现在可以看看*Looper.loop();*这句代码到底做了什么了loop方法中的代码如下

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        final Looper me = myLooper();//通过myLooper方法拿到与主线程绑定的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(); // 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 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);
                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();
        }
    }

上面的代码,我已经进行了部分注释,这里有一句代码非常重要

 msg.target.dispatchMessage(msg);

执行到这句代码,说明已经从消息队列中拿到了消息,还记得msg.target吗?就是Message中的target变量呀!也就是发送消息的那个Handler,所以这句代码的本质就是调用了Handler中的dispatchMessage(msg)方法,代码分析到这里是不是有点小激动了呢!稳住!下面看下dispatchMessage(msg)这个方法,代码如下

/**
     * Handle system messages here.
     */
    public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

现在来一句句的来分析上面的代码,先看下这句

if (msg.callback != null) {
            handleCallback(msg);
        }

msg.callback就是Runnable对象,当msg.callback不为null时会调用 handleCallback(msg)方法,先来看下 handleCallback(msg)方法,代码如下

 private static void handleCallback(Message message) {
        message.callback.run();
    }

上面的代码就是调用了Runnable的run方法。那什么情况下**if (msg.callback != null)**这个条件成立呢!还记得使用Handler的另一种方法吗?就是调用Handler的post方法呀!这里说明一下,使用Handler其实是有两种方法的

  1. 使用Handler的sendMessage方法,最后在handleMessage(Message msg)方法中来处理消息。
  2. 使用Handler的post方法,最后在Runnable的run方法中来处理,代码如下
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mTimeCycle,mStopCycle;
    private Runnable mRunnable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() {
        mTimeCycle = findViewById(R.id.btn_time_cycle);
        mTimeCycle.setOnClickListener(this);
        mStopCycle = findViewById(R.id.btn_stop_cycle);
        mStopCycle.setOnClickListener(this);
        mRunnable = new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "正在循环!!!", Toast.LENGTH_SHORT).show();
                mHandler.postDelayed(mRunnable, 1000);
            }
        };
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_time_cycle:
                mHandler.post(mRunnable);
                break;
            case R.id.btn_stop_cycle:
                mHandler.removeCallbacks(mRunnable);
                break;
        }
    }
}

第一种方法,我们已经分析了,下面来分析一下第二种使用方式的原理,先看下Handler的post的方法做了什么,代码如下

/**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is 
     * attached. 
     *  
     * @param r The Runnable that will be executed.
     * 
     * @return Returns true if the Runnable was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    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;
    }

由上面的代码不难看出,post方法最终也是将Runnable封装成消息,然后将消息放进MessageQueue中。下面继续分析dispatchMessage方法中的代码

else {
        //if中的代码其实是和if (msg.callback != null) {handleCallback(msg);} 
        //原理差不多的,只不过mCallback是Handler中的成员变量。
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
    //当上面的条件都不成立时,就会调用这句代码
            handleMessage(msg);
        }

上面的代码就不分析了,我已经在代码中进行了注释,下面再看下**handleMessage(msg)**这个方法,代码如下

/**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(Message msg) {
    }

其实,他就是一个空方法,具体的代码让我们自己重写这个方法进行处理。代码分析到这里,已经可以给出下面问题的答案了。

  • Handler明明是在子线程中发的消息怎么会跑到主线程中了呢?
  • Handler的发送消息handleMessage又是怎么接收到的呢?

在子线程中Handler在发送消息的时候已经把自己与当前的message进行了绑定,在通过Looper.loop()开启轮询message的时候,当获得message的时候会调用 与之绑定的Handler的**handleMessage(Message msg)**方法,由于Handler是在主线程创建的,所以自然就由子线程切换到了主线程。

总结

  上面已经嗯将Handler的源码分析了一遍,现在来进行一些总结:

1、Handler的工作原理

  在使用Handler之前必须要调用Looper.prepare()这句代码,这句代码的作用是将Looper与当前的线程进行绑定,在实例化Handler的时候,通过Looper.myLooper()获取Looper,然后再获得Looper中的MessageQueue。在子线程中调用Handler的sendMessage方法就是将Message放入MessageQueue中,然后调用Looper.loop()方法来从MessageQueue中取出Message,在取到Message的时候,执行 **msg.target.dispatchMessage(msg);**这句代码,这句代码就是从当前的Message中取出Handler然后执行Handler的handleMessage方法。

2、Handler、Message、MessageQueue以及Looper之间的关系

  在介绍它们之间的关系之前,先说一下它们各自的作用。

  • Handler:负责发送和处理消息。
  • Message:用来携带需要的数据。
  • MessageQueue:消息队列,队列里面的内容就是Message。
  • Looper:消息轮巡器,负责不停的从MessageQueue中取Message。

它们的关系如下图(图片来源于网上)

3、在子线程中使用Handler

  在子线程中使用Handler的方式如下

class LooperThread extends Thread {
    public Handler mHandler;
    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };
        Looper.loop();
    }
}

上面的代码来自官方的源码。

结束语

  本文将Handler的机制详细讲解了一遍,包括在面试中有关Handler的一些问题,在文章中也能找到答案。顺便说下阅读代码应该注意的地方,在分析源码之前应该知道你分析代码的目的,就是你为了得到什么答案而分析代码;在分析代码时切记要避轻就重,不要想着要搞懂每句代码做了什么,要找准大方向。文中的代码已上传到GitHub,可以在这里获取,与Handler有关的源码在我上传的源码的handler包中。


相关文章
|
6天前
|
ARouter IDE 开发工具
Android面试题之App的启动流程和启动速度优化
App启动流程概括: 当用户点击App图标,Launcher通过Binder IPC请求system_server启动Activity。system_server指示Zygote fork新进程,接着App进程向system_server申请启动Activity。经过Binder通信,Activity创建并回调生命周期方法。启动状态分为冷启动、温启动和热启动,其中冷启动耗时最长。优化技巧包括异步初始化、避免主线程I/O、类加载优化和简化布局。
26 3
Android面试题之App的启动流程和启动速度优化
|
7天前
|
安全 Java 编译器
Android面试题之Java 泛型和Kotlin泛型
**Java泛型是JDK5引入的特性,用于编译时类型检查和安全。泛型擦除会在运行时移除类型参数,用Object或边界类型替换。这导致几个限制:不能直接创建泛型实例,不能使用instanceof,泛型数组与协变冲突,以及在静态上下文中的限制。通配符如<?>用于增强灵活性,<? extends T>只读,<? super T>只写。面试题涉及泛型原理和擦除机制。
16 3
Android面试题之Java 泛型和Kotlin泛型
|
4天前
|
缓存 JSON 网络协议
Android面试题:App性能优化之电量优化和网络优化
这篇文章讨论了Android应用的电量和网络优化。电量优化涉及Doze和Standby模式,其中应用可能需要通过用户白名单或电池广播来适应限制。Battery Historian和Android Studio的Energy Profile是电量分析工具。建议减少不必要的操作,延迟非关键任务,合并网络请求。网络优化包括HTTPDNS减少DNS解析延迟,Keep-Alive复用连接,HTTP/2实现多路复用,以及使用protobuf和gzip压缩数据。其他策略如使用WebP图像格式,按网络质量提供不同分辨率的图片,以及启用HTTP缓存也是有效手段。
27 9
|
8天前
|
网络协议 算法 安全
小米安卓春招面试一面
小米安卓春招面试一面
22 3
|
8天前
|
缓存 网络协议 Java
Android面试题之Java网络通信基础知识
Socket是应用与TCP/IP通信的接口,封装了底层细节。网络通信涉及连接、读写数据。BIO是同步阻塞,NIO支持多路复用(如Selector),AIO在某些平台提供异步非阻塞服务。BIO示例中,服务端用固定线程池处理客户端请求,客户端发起连接并读写数据。NIO的关键是Selector监控多个通道的事件,减少线程消耗。书中推荐《Java网络编程》和《UNIX网络编程》。关注公众号AntDream了解更多。
18 2
|
9天前
|
XML JSON Java
Android面试题 之 网络通信基础面试题
序列化对比:Serializable码流大、性能低;XML人机可读但复杂;JSON轻量、兼容性好但空间消耗大;ProtoBuff高效紧凑。支持大量长连接涉及系统限制调整、缓冲区优化。select/poll/epoll是IO多路复用,epoll在高连接数下性能更优且支持边缘触发。水平触发持续通知数据,边缘触发仅通知新数据。直接内存减少一次拷贝,零拷贝技术如sendfile和MMAP提升效率。关注公众号&quot;AntDream&quot;了解更多技术细节。
12 1
|
9天前
|
Android开发 Kotlin
Android面试题 之 Kotlin DataBinding 图片加载和绑定RecyclerView
本文介绍了如何在Android中使用DataBinding和BindingAdapter。示例展示了如何创建`MyBindingAdapter`,包含一个`setImage`方法来设置ImageView的图片。布局文件使用`&lt;data&gt;`标签定义变量,并通过`app:image`调用BindingAdapter。在Activity中设置变量值传递给Adapter处理。此外,还展示了如何在RecyclerView的Adapter中使用DataBinding,如`MyAdapter`,在子布局`item.xml`中绑定User对象到视图。关注公众号AntDream阅读更多内容。
17 1
|
11天前
|
Android开发
Android面试题之activity启动流程
该文探讨了Android应用启动和Activity管理服务(AMS)的工作原理。从Launcher启动应用开始,涉及Binder机制、AMS回调、进程创建、Application和Activity的生命周期。文中详细阐述了AMS处理流程,包括创建ClassLoader、加载APK、启动Activity的步骤,以及权限校验和启动模式判断。此外,还补充了activity启动流程中AMS的部分细节。欲了解更多内容,可关注公众号“AntDream”。
13 1
|
3天前
|
Java Android开发 Kotlin
Android面试题:App性能优化之Java和Kotlin常见的数据结构
Java数据结构摘要:ArrayList基于数组,适合查找和修改;LinkedList适合插入删除;HashMap1.8后用数组+链表/红黑树,初始化时预估容量可避免扩容。SparseArray优化查找,ArrayMap减少冲突。 Kotlin优化摘要:Kotlin的List用`listOf/mutableListOf`,Map用`mapOf/mutableMapOf`,支持操作符重载和扩展函数。序列提供懒加载,解构用于遍历Map,扩展函数默认参数增强灵活性。
11 0
|
11天前
|
vr&ar 数据库 Android开发
Android面试题之ActivityManagerService的启动流程
本文探讨了Android系统的SystemServer启动过程,包括创建SystemContext、引导服务、启动各类核心服务以及AMS的启动和初始化。AMS负责管理activity、广播队列、provider等,并设置SystemProcess,安装系统Provider。当AMS调用SystemReady时,系统UI准备启动,启动Launcher。文中还对比了init、zygote和system_server进程的角色。最后推荐了两本关于Android内核剖析的书籍:柯元旦教授的《Android内核剖析》和罗升阳的《Android系统源代码情景分析》。关注公众号AntDream获取更多内容。
12 0