Handler消息机制

目录

大纲

概念

概述

详细描述

执行流程

初步使用

在主线程中使用

sendMessage(Message)

post(Runnable)

在次线程中使用

我的Demo

源码原理

相关面试题

1:handleMessage究竟在哪个线程执行

2:子线程中,是否可以直接new一个Handler?

3:如何解决Handler引起的内存泄露?


感谢

感谢developer.android.google!~

感谢各位大大提供了各种学习资料 !~

感谢自己 感谢你们!~

学习资料:

Handler消息传递机制浅析

Android多线程:手把手带你深入Handler源码分析(上)

Android多线程:手把手带你深入Handler源码分析(下)

大纲

Handler消息机制

 

概念

Handler,英[ˈhændlə(r)] 美[ˈhændlər] ,译为处理器;句柄;处理程序;处理者;处理

概述

很多时候,耗时任务都是需要放到次线程去执行的,次线程任务执行完毕之后,主线程需要及时的进行一个UI的更新与反馈以告知用户,那么如何能够及时?主线程何时才知道次线程完成了任务?——Handler,就是主次线程沟通的一个桥梁。

详细描述

查阅官方对于Handler的描述可知,Handler 继承于Object,它允许我们发送和处理与线程MessageQueue关联的Message与Runnable对象。每个Handler都与一个线程以及该线程的消息队列关联。当我们创建一个新的Handler时,它被绑定到正在创建它的线程/该线程的消息队列——从那时起,它将消息和runnables传递给该消息队列并在消息从消息队列中取出时,执行它们。

Handler有两个主要用途:

(1)安排messages和runnables在将来的某个时刻被执行;

(2)将在不同的线程上执行的操作排入队列。

整个Handler的消息调度离不开以下几个方法:

(1)post(Runnable)

(2)postAtTime(java.lang.Runnable, long)

(3)postDelayed(Runnable, Object, long)

(4)sendEmptyMessage(int)

(5)sendMessage(Message)

(6)sendMessageAtTime(Message, long)

(7)sendMessageDelayed(Message, long)

post(Runnable),将Runnable对象添加到消息队列message queue中,该Runnable对象将在该Handler所连接的线程上运行;sendMessage(Message),它将在消息队列message queue的末尾添加一条消息,而这条消息,它是在当前时间之前的所有挂起消息之后。它将以handleMessage(Message)的形式在附加到此Handler的线程中接收。

当向Handler发布或发送消息时,可以允许在message queue准备好处理该项时立即处理该项,或者指定处理该项之前的延迟或处理该项的绝对时间。后两者允许实现超时、标记和其他基于时间的行为。

为应用程序创建进程时,其主线程专用于运行消息队列message queue,该队列负责管理*应用程序对象(活动,广播接收器等)及其创建的任何窗口。我们可以创建自己的线程,并通过Handler与主应用程序线程进行通信。这是通过调用post或sendMessage方法完成的,然后,将在Handler的消息队列message queue中调度给定的Runnable或Message,并在适当时进行处理。

执行流程

Handler执行流程如图所示:

Handler消息机制

4个关键词:

//1,Looper:循环器,用于管理MessageQueue,不断地循环消息,不断地从中取出Message分发给对应的Handler处理,每个线程只能够有一个Looper。

//2,Message:消息对象。

//3,MessageQueue:存放消息对象的消息队列,队列它是一种先进先出的数据结构。

//4,Handler:处理消息对象的处理器。

//注意:系统在创建主线程的时候,会初始化一个Looper对象,同时也会把它关联的MessageQueue创建好,所以我们的Handler在主线程中实例化时,不需要额外的对Looper进行操作(就可以进行信息的发送与处理了)。

初步使用

在主线程中使用

sendMessage(Message)

使用sendMessage(Message),有如下几个步骤:

//1:在主线程创建一个Handler静态内部类

//2:在主线程实例化第1步中创建的静态内部类

//3:创建一个子线程

//4:在子线程中,通过Handler对象调用sendMessage(Message)方法,将消息发送到消息队列中

//请看代码:

public class HandlerSendMessageTest extends AppCompatActivity {
    TextView test;
    Handler myHandler;

    //1:在主线程创建一个Handler静态内部类
    // 静态内部类不会持有外部类的引用 再结合WeakReference使用 可以预防内存泄漏
    private static class MyHandler extends Handler {

        WeakReference<MainActivity> weakReferenceAct;

        public MyHandler(MainActivity mainActivity) {
            weakReferenceAct = new WeakReference<MainActivity>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    weakReferenceAct.get().test.setText("myHandler.sendMessage(msg)");
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        test = findViewById(R.id.test);

        //2:实例化内部类
        myHandler = new MyHandler(this);

        //3:举个栗子 创建一个线程
        new Thread() {
            @Override
            public void run() {
                super.run();
                SystemClock.sleep(2000);
                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = "nhan";

                //4:在子线程中,通过Handler对象调用sendMessage(Message)方法,将消息发送到消息队列中
                myHandler.sendMessage(msg);
            }
        }.start();
    }
}

post(Runnable)

//1:在主线程中实例化一个Handler,得到一个Handler的对象

//2:创建一个子线程

//3:在子线程中,直接调用Handler对象.post(Runnable)方法传入一个Runnable,而后进行相关的UI操作

//请看代码:

public class HandlerPostMessageTest extends AppCompatActivity {
    TextView test;
    Handler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        test = findViewById(R.id.test);

        //1:在主线程中实例化一个Handler,得到一个Handler的对象
        handler = new Handler();

        //2:举个栗子 创建一个子线程
        new Thread() {
            @Override
            public void run() {
                super.run();
                //3:在子线程中,直接调用Handler对象.post(Runnable)方法传入一个Runnable,而后进行相关的UI操作
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        test.setText("handler.post(Runnable)");
                    }
                });

            }
        }.start();
    }
}

在次线程中使用

public class LooperPrepare extends AppCompatActivity {
    Handler handler;
    TextView test;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        test = findViewById(R.id.test);

        //1:创建一个子线程
        new Thread() {
            @Override
            public void run() {
                super.run();
                //2:在子线程中 准备Looper对象
                Looper.prepare();
                //3:实例化Handler 并重写handleMessage()方法处理消息
                handler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        switch (msg.what) {
                            case 1:
                                test.setText("在子线程中使用Handler");
                                break;
                            default:
                                break;
                        }
                    }
                };
                //4:调用Looper.loop() 运行消息队列
                Looper.loop();
            }
        }.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Message msg = Message.obtain();
        msg.what = 1;
        msg.obj = "nhan";
        handler.sendMessage(msg);
    }
}

我的Demo

先欠着吧?回头一定补上 .. - - ,

源码原理

Handler消息机制能够正常运作,如前面的执行流程图所示,它跟Looper、MessageQueue之间是密不可分的,所以对于Handler消息机制源码的分析,以Handler在次线程中的使用为栗子,从头到尾进行分析,那么就慢慢来吧 ——

在子线程中使用Handler,我们首先要能够获取到一个Looper的对象,对于Looper,它最重要的两块,就是prepare()和loop()两个方法:

prepare()源码如下:

    /** Initialize the current thread as a looper.
      * This gives you a chance to create handlers that then reference
      * this looper, before actually starting the loop. Be sure to call
      * {@link #loop()} after calling this method, and end it by calling
      * {@link #quit()}.
      */
    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));
    }

我们可以看到,prepare()最终是返回一个sThreadLocal.set(new Looper(quitAllowed)):

     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

而这个new Looper(quitAllowed)是作为参数,传入到sThreadLocal.set(new Looper(quitAllowed))当中,可以看到Looper操作中,有new一个消息队列MessageQueue:

    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

所以我们说,系统在创建主线程的时候,会初始化一个Looper对象,同时也会把它关联的MessageQueue创建好,所以我们的Handler在主线程中实例化时,不需要额外的对Looper进行操作。

那么在创建好Looper对象与MessageQueue之后,就需要在创建好的线程内对Handler进行实例化、重写handleMessage()方法 .. 并开启消息队列的循环,进而去对消息队列中的消息进行轮询。

此时开启消息队列的循环,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();
        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 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 traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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()方法将消息从消息队列中移出来的:

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 (DEBUG) Log.v(TAG, "Returning message: " + msg);
                        msg.markInUse();
                        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(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;
        }
    }

不断的轮询,不断的将消息取出,不断的去执行对应的消息,这就是我们的Handler消息机制了。

最后,我们分析sendMessage(Message)与post(Runnable)到底有什么差别?

如下图,是sendMessage(Message)与post(Runnable)发送消息,所经过的所有方法:

Handler消息机制

它们最大的差别就是:sendMessage(Message)需要传入Message,而post(Runnable)需要传入Runnable。

细细分析,post(Runnable)最终return的是sendMessageDelayed(getPostMessage(r), 0):

    /**
     * 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);
    }

而sendMessageDelayed(getPostMessage(r), 0)我们又可以看到,它需要传入一个参数getPostMessage(r),这个参数,最终返回的也是一个Message类型的对象。

    private static Message getPostMessage(Runnable r) {
        Message m = Message.obtain();
        m.callback = r;
        return m;
    }

    private static Message getPostMessage(Runnable r, Object token) {
        Message m = Message.obtain();
        m.obj = token;
        m.callback = r;
        return m;
    }

接下来,post(Runnable)走的都是与sendMessage(Message)相同的方式,所以我们可以认为,它们的本质其实都是相同的,最终的最终,也只是为了把消息压入消息队列MessageQueue中。

自此,整个流程分析完毕。

相关面试题

面试题传送门:200斤牌面试必备Handler面试题 请安利(不停更)

 

 

 

上一篇:android 和主线程有关的小问题


下一篇:Looper.getMainLooper()使用误区