Handler源码解析

日常得开发中经常使用到Handler,所以就看下源码,了解下运行得原理。

经度使用方法,这里不考虑内存得泄露。

private static final int TAG = 0x99;
final Handler mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what == TAG){
                    tvResult.setText("Work Done");
                }
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                //Time-consuming tasks
                mHandler.sendEmptyMessage(TAG);
            }
        }).start();

子线程完成耗时操作,然后通知主线程更新UI,看下Handler得构造方法。

   

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

可以看到首先传入一个null得CallBack和 false async,看下CallBack得实现。

   

 /**
     * Callback interface you can use when instantiating a Handler to avoid
     * having to implement your own subclass of Handler.
     *
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    public interface Callback {
        public boolean handleMessage(Message msg);
    }

这个CallBack 就是我们使用得时候,重写得handleMessage。接着回到构造函数,对mQueue,mLooper,mCallback 进行初始化,显然Handler得正常使用,必须要使用到Looper和Queue,如果Looper为null,则会抛出异常。接着看下Looper得源码。

在使用得时候需要Looper.prepare(),先看下源码实现。

   

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

首先在当前线程中保存了一个新得Looper,并且每个线程只能有一个Looper,所,每个线程调用Looper.prepare()就可以给每个线程准备一个Looper,ThreadLocal是一个可以为每一个线程保存不同数据得工具,每个线程调用sThreadLocal.set(new 

Looper(quitAllowed));都可以保存一个Looper。接着看下Looper得构造函数。
    private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

Looper是一个final声明得类,禁止了继承,在构造函数里创建了一个消息队列MessageQueue,和获取了当前执行得线程。接着看下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();
        }
    }

loop是一个死循环,从queue中不断得取出消息,当message为null时跳出循环,然后运行msg.target.dispatchMessage(msg);这里得msg.target就是发送得msg得handler。

Looper得功能就是先调用Looper.perpare给线程添加一个Looper,再启动loop后持续得维护一个Queue,在合适得时机将Queue中得消息通过dispatchMessage传给Handler处理,如果Queue中没有消息,则queue.next会阻塞直到有消息来,再继续读取,并且queue.next中如果消息出队列了,则删除消息。

在主线程中使用Handler不用手动去调用Looer得两个方法来启动,因为主线程默认带有Looper.


 

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

当prepareMainLooper被调用完后,主线程就默认带有一个Looper,这个函数被调用的是在ActivityThread里面在main方法中得。

public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();
        // 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());
        AndroidKeyStoreProvider.install();
        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);
        Process.setArgV0("");
        Looper.prepareMainLooper();
        ActivityThread thread = new ActivityThread();
        thread.attach(false);
        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();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
    }

在启动主线程得时候调用了Looper.prepareMainLooper(),所以在主线程上使用handler不哟领手动调用Looper了。

接着看下消息发送sendMessage得源码。

 /**
     * Pushes a message onto the end of the message queue after all pending messages
     * before the current time. It will be received in {@link #handleMessage},
     * in the thread attached to this handler.
     *  
     * @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.
     */
    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

最终运行得是sendMessageAtTime方法。
   

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

判断队列queue是否为null,接着调用enqueueMessage,看下实现。

   

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

首先将msg.target赋值为本身,然后调用queue把消息压入队列中,等待发送。接着看下最终消息回调得dispatchMessage函数得源码。

   

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

比较简单,主要就是调用了我们重写得handleMessage函数。

整个Handler得流程就分析完了,首先我们在生成handler的时候,提供一个处理Msg的逻辑,这也是最后Message具体内容处理的位置。并且在生成Handler之前保证相应线程Looper存在并且能够正常工作,这时Looper能够不断监视一个MessgeQueue,之后我们可能需要处理一些异步的工作,让某个线程持有该handler的引用,这就是线程切换的关键,这样可以让其他线程调用handler最终将异步的信息传递给handler所在的线程。接下来就是做一些耗时任务或其他操作,并在完成之后将一些信息封装成Message,然后再使用我们的handler,发送message即可。此时message 会被放入MessageQueue,如果相关Looper检测到了message的到来,并且相关性线程并未阻塞,就把message从队列里放出来,再传递给handler,进而调用handler的dispatchMessage完成message的处理,这样就完成了线程之间的切换。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值