Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

Android Handler分析

$
0
0

Android Handler分析

标签(空格分隔): handler

最近面试总是被问到handler相关的东西,那就静下心来,仔细分析一下handler的源码,看一下内部到底是个什么鬼,也好出去装逼不是。

  • 首先看一下handler的构造方法,都有些什么鬼,我把源码的注释去掉了,想看的自己去源码里看
   private static final boolean FIND_POTENTIAL_LEAKS = false;

 /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     */
    public Handler() {
        this(null, false);
    }


    public Handler(Callback callback) {
        this(callback, false);
    }


    public Handler(Looper looper) {
        this(looper, null, false);
    }

    public Handler(Looper looper, Callback callback) {
        this(looper, callback, false);
    }

    public Handler(boolean async) {
        this(null, async);
    }

/**
* @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
each {@link Message} that is sent to it or {@link Runnable} that is posted to it.也就是说async=true的时候,handler sent或者post的message,均是异步的
*
*/
    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: " +
//返回全路径的完整的类型,类似class.getName()用法                    
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;
    }


    public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

主要看一下37行–55行:
我们看到FIND_POTENTIAL_LEAKS 默认是false,当FIND_POTENTIAL_LEAKS=true的时候,貌似并没有什么卵用,直接略过。继续向下看,
47行:

mLooper = Looper.myLooper()
 if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }

如果Looper=null,直接就抛出异常,这也就解释了为什么我们在子线程创建Handler之前,要调用一下Looper.prepare(),否则会报错。一个线程只能有一个Looper
60行:可以看到MessageQueue是Looper来维护的
再看10-17行:就知道我们在activity或者fragment中,实现handler有两种方式1,实现Callback接口,来处理Message.2,重写内部handleMessage(Message msg)来处理Message。

再来看下一段代码:

    public final Message obtainMessage()
    {
        return Message.obtain(this);
    }

    public final Message obtainMessage(int what)
    {
        return Message.obtain(this, what);
    }

    public final Message obtainMessage(int what, Object obj)
    {
        return Message.obtain(this, what, obj);
    }

    public final Message obtainMessage(int what, int arg1, int arg2)
    {
        return Message.obtain(this, what, arg1, arg2);
    }

    public final Message obtainMessage(int what, int arg1, int arg2, Object obj)
    {
        return Message.obtain(this, what, arg1, arg2, obj);
    }

    Message源码:

        public static Message obtain(Handler h, int what, 
            int arg1, int arg2, Object obj) {
        Message m = obtain();
        m.target = h;
        m.what = what;
        m.arg1 = arg1;
        m.arg2 = arg2;
        m.obj = obj;

        return m;
    }

        /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     消息队列中消息的复用
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

由以上源码可以看出:android api已经给我们提供了封装Message的方法

//实现Message的复用,
Message msg = handler.obtain();
Message msg = Message.obtain()

所以不要再直接

//不要这样使用
Message msg = new Message();

继续向下看源码:


    public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }


    public final boolean postAtTime(Runnable r, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r), uptimeMillis);
    }


    public final boolean postAtTime(Runnable r, Object token, long uptimeMillis)
    {
        return sendMessageAtTime(getPostMessage(r, token), uptimeMillis);
    }


    public final boolean postDelayed(Runnable r, long delayMillis)
    {
        return sendMessageDelayed(getPostMessage(r), delayMillis);
    }


    public final boolean postAtFrontOfQueue(Runnable r)
    {
        return sendMessageAtFrontOfQueue(getPostMessage(r));
    }


除了最后一个方法外,其余的方法应该都很眼熟吧,使用也没什么难的
最后一个方法26-29行:
向实现了Runnable接口的对象发送一个消息。使得Runnable对象r能够在消息队列的下一个迭代中继续执行。
这个方法只能在非常特殊的情况下才有用—它很容易饿死在消息队列中,导致排序问题或者其他难以预料的负面影响,说实话,我也没用过

再来看一下sendMessage相关的几个方法:

  public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }


    public final boolean sendEmptyMessage(int what)
    {
        return sendEmptyMessageDelayed(what, 0);
    }


    public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }



    public final boolean sendEmptyMessageAtTime(int what, long uptimeMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageAtTime(msg, uptimeMillis);
    }

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


    public final boolean sendMessageAtFrontOfQueue(Message msg) {
        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, 0);
    }

    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

从上往下看,到最后全部都交给了MessageQueue去处理了,queue.enqueueMessage(msg, uptimeMillis)这个方法应该就是入队了,看下源码

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;
    }

2-7行:是否已经在处理中和是否有处理它的Handler,
10-16行:检查是否在中止,如果是,那么message直接回收
22行-end:就是入栈操作了
在这其中作了一些减少同步操作的优化,即使当前消息队列已经处于 Blocked 状态,且队首是一个消息屏障(这里是通过 p.target ==null来判断队首是否是消息屏障),并且要插入的消息是所有异步消息中最早要处理的才会 needwake激活消息队列去获取下一个消息。

继续往下看:


 public final void removeCallbacks(Runnable r)
    {
        mQueue.removeMessages(this, r, null);
    }


    public final void removeCallbacks(Runnable r, Object token)
    {
        mQueue.removeMessages(this, r, token);
    }

    public final void removeMessages(int what) {
        mQueue.removeMessages(this, what, null);
    }


    public final void removeMessages(int what, Object object) {
        mQueue.removeMessages(this, what, object);
    }


    public final void removeCallbacksAndMessages(Object token) {
        mQueue.removeCallbacksAndMessages(this, token);
    }

这里Remove操作也是全部交给了MessageQueue去处理了.

再看一下Looper有什么鬼:


    // sThreadLocal.get() will return null unless you've called prepare().
    static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
    final MessageQueue mQueue;
    final Thread mThread;

从代码看出,Looper主要就是维护了这三个东西,ThreadLocal,MessageQueue,Thread;

  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.prepare(),然后再调用Loop.myLooper()才能获得Looper;而且也能知道一个线程只能有一个Looper,依据就在这里。

至于为毛UI线程不需要调用Looper.prepare(),看下面的代码就知道了


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

    /**
     * Returns the application's main looper, which lives in the main thread of the application.
     */
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

这下就清楚了,Android 系统已经为我们准备好了MainLooper,不需要我们再主动去调用Looper.prepare(),

剩下只有Looper的核心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();

        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();
        }

因此要想Looper开始工作还要调用Loop.loop(),进入消息循环
18行—从消息队列中取出消息
31行—handler分发消息dispatchMessage(msg);
48行–消息回收

那我们在回过头来看一下Handler.dispatchMessage(msg),看看其中是怎么处理的

 public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }

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

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

    public interface Callback {
        public boolean handleMessage(Message msg);
    }

先看1-12行:如果msg.callback!=null,直接执行handleCallback(msg)方法,然后跟踪过去,你发现直接调用了run(),这也说明了Handler.post(Runnable)其实是运行在Handler绑定的线程中的,并不是子线程
再往下:你会发现这里有两种handleMessage的方案,一种实现实现Handler.Callback 调用callback.handleMessage(),另一种直接handleMessage();

下面轮到Message了,看一下Message内部是个什么样子,看看有没有我们想象的那么神秘:

    public int what;
    public int arg1; 
    public int arg2;
    public Object obj;

    /**
     * Optional Messenger where replies to this message can be sent.  The
     * semantics of exactly how this is used are up to the sender and
     * receiver.
     */
    public Messenger replyTo;

    public int sendingUid = -1;
    static final int FLAG_IN_USE = 1 << 0;

   static final int FLAG_ASYNCHRONOUS = 1 << 1;

   static final int FLAGS_TO_CLEAR_ON_COPY_FROM = FLAG_IN_USE;

    int flags;

   long when;

    Bundle data;

    Handler target;

   Runnable callback;

    Message next;

    private static final Object sPoolSync = new Object();
    private static Message sPool;
    private static int sPoolSize = 0;

    private static final int MAX_POOL_SIZE = 50;

    private static boolean gCheckRecycle = true;


    /** @hide */
    public static void updateCheckRecycle(int targetSdkVersion) {
        if (targetSdkVersion < Build.VERSION_CODES.LOLLIPOP) {
            gCheckRecycle = false;
        }
    }

    public void recycle() {
        if (isInUse()) {
            if (gCheckRecycle) {
                throw new IllegalStateException("This message cannot be recycled because it "
                        + "is still in use.");
            }
            return;
        }
        recycleUnchecked();
    }

    void recycleUnchecked() {
        // Mark the message as in use while it remains in the recycled object pool.
        // Clear out all other details.
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;

        synchronized (sPoolSync) {
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
    }


    /*package*/ boolean isInUse() {
        return ((flags & FLAG_IN_USE) == FLAG_IN_USE);
    }

    /*package*/ void markInUse() {
        flags |= FLAG_IN_USE;
    }

看数据结构,Message就是一个链式结构的设计,里面只有一个核心的recycleUnchecked()方法,实现消息的重置和复用

说了这么多,有点晕乎乎的感觉,那就用图形化来说明一下:

此处输入图片的描述

此处输入图片的描述

此处输入图片的描述

再来个例子,主线程向子线程发送消息,

  public class MyThread extends Thread implements Handler.Callback{

    public Handler mHandler;
    public Handler secondHandler;

    @Override
    public void run(){
        Looper.prepare();
        mHandler = new Handler(this);
        secondHandler = new Handler(){
            @Override
            public void  handleMessage(Message msg) {
                System.out.println("msg----"+msg.toString());

            }
        };
        Looper.loop();
    }

    @Override
    public boolean handleMessage(Message msg) {
        System.out.println("msg----"+msg.toString());
        //记得要关闭 Looper.myLooper().quit();
        return false;
    }

}


public class MainActivity extends Activity {

    MyThread thread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        thread = new MyThread();
        thread.start();

    }

    @Override
    protected void onResume(){
        super.onResume();
        thread.mHandler.sendEmptyMessage(3);
        thread.secondHandler.sendEmptyMessage(55);
    }
}

Handler相关内容完美结束,尼玛再也不怕出去谁问handler机制了,如果有错误的地方,希望大大们提醒我一下。

作者:baidu_17508977 发表于2016/11/25 18:05:47 原文链接
阅读:57 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>