深入浅出Handler的使用

Handler概述

我们都悉知在Android中,如果某项任务的执行时间太长就会导致程序ANR(Application Not Response),所以我们都会通过将耗时操作转移到子线程执行,从而避免ANR的出现。但是Android规定UI的更新只能在主线程中进行,一旦在子线程中访问UI就会抛出异常。而Handler正是Android为了解决这一矛盾提供的解决方式。
首先明确几个需要着重理解的概念:

  • Message:消息,携带了描述信息和数据,是Handler进行处理的对象
  • MessageQueue:消息队列,用来存放所有通过Handler发布的消息,因为是队列,所以是先进先出的。
  • Looper:不断循环从MessageQueue中取出Message,并交给相应的Handler进行处理。
  • Handler:负责将Message添加到消息队列以及从Looper抽取出来的Message进行处理。

Handler源码

创建Handler实例

首先先进行Handler的实例创建

new Handler();
    Log.d("main", "handler1");

new Thread(new Runnable() {
    @Override
    public void run() {
      new Handler();
      Log.d("thread", "handler2");
    }
}).start();

我们可以发现,当执行到新线程中创建Handler时会抛出异常:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

而如果我们在代码中把Looper.prepare()加上,就可以正常运行:

new Thread(new Runnable() {
    @Override
    public void run() {
      Looper.prepare();
      new Handler();
      Log.d("thread", "handler2");
    }
}).start();

我们回过头来看看Handler实例的时候都做了些什么:

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

可以看到,当mLooper == null时就会抛出刚所说的异常。那么Looper对象何时为空呢?

public static final Looper myLooper() {  
    return (Looper)sThreadLocal.get();  
}

可以看到Looper对象是从sThreadLocal中取出。而通过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));
    }

那么为什么在主线程中创建Handler的时候没有报错呢?答案就在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());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

       //关键点
        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");
    }
public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

可以看到在Activity生命周期开始的后就通过调用Looper.prepareMainLooper()创建了一个主线程的Looper

所以主线程可以直接创建Handler对象,而子线程则需要先调用Looper.prepare()

Handler消息发送

先写一个简单的消息发送示例:

    Handler handler = new Handler();
    Message msg = new Message();
    msg.arg1 = 1;
    Bundle bundle = new Bundle();
    bundle.putString("data", "test");
    msg.setData(bundle);
    handler.sendMessage(msg);

Handler提供了几个发送的方法,其中经过辗转后面都会调用该方法sendMessageAtTime(Message msg, long uptimeMillis)

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

通过enqueueMessage()方法进行消息入队。
MessageQueue.enqueueMessage(Message msg, long when)

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

因为存在多线程插入消息,所以需要加上同步;参数when=SystemClock.uptimeMillis()+delayMillis,如果调用的是post方法则delayMillis为0;mMessages代表的是消息队列的头部,当它为空的时候表示队列没有消息,并且根据当前的Loop线程的状态来判断是否需要唤醒队列;否则插入消息并且根据when来对msg进行队列的排序;最后判断是否需要唤醒Looper线程,至此完成了消息的加入。

Handler消息处理

在上面提到的ActivityThread.main()方法中,不仅调用了Looper.prepareMainLooper,而且也调用了Looper.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
            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();
        }
    }

首先获取到当前LooperMessageQueue实例,然后通过一个死循环经queue.next()方法获取下一个Message,当MessageQueue为空,则阻塞队列。而每当有一个消息出队的时候,都会经过msg.target.dispatchMessage(msg),通过上面我们知道msg.target其实就是Handler
那么我们就来到Handler.dispatchMessage()

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

如果mCallback不为空,则执行mCallback.handleMessage(msg);否则走Handler.handleCallback(msg)方法。所以我们可以通过handleMessage()方法获取到之前发送的消息!

Handler注意事项

Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
    }
  };

由于java中非静态内部类和匿名内部类都会隐式持有当前类的外部引用,而上图所示的使用方式正是因为Handler是非静态内部类所以其持有当前Activity的隐式引用,如果Handler没有被释放,其所持有的外部引用也就是Activity也无法被释放,本该被回收的对象不能被回收而停留在堆内存中,这就产生了内存泄漏。

而面对这种情况,我们通常的解决方式就是使用静态内部类并继承Handler(或者也可以单独存放成一个类文件)。因为静态的内部类不会持有外部类的引用,所以不会导致外部类实例的内存泄露。当你需要在静态内部类中调用外部的Activity时,我们可以使用弱引用来处理。如下所示:

private static class MyHandler extends Handler {

    //持有弱引用HandlerActivity,GC回收时会被回收掉.  
    private final WeakReference<MainActivity> mActivty;

    public MyHandler(MainActivity activity) {
      mActivty = new WeakReference<>(activity);
    }

    @Override
    public void handleMessage(Message msg) {
      MainActivity activity = mActivty.get();
      super.handleMessage(msg);
      if (activity != null) {
        //执行业务逻辑  
      }
    }
  }

至此完成对Handler分析。

版权声明:

本文标题:深入浅出Handler的使用

作者:Rabtman

原始链接:https://rabtman.com/2017/05/03/handler_source/

本文采用署名-非商业性使用-禁止演绎4.0进行许可。

非商业转载请保留以上信息。商业转载请联系作者本人。