Android开发Handler源码分析

为什么使用Handler

Android中UI控件的访问是线程不安全的,加锁同步访问会影响性能,因此设置只能一个线程更新UI,就是主线程,或者说是UI线程。在UI线程中不能进行耗时的操作,耗时操作需要开启一个新的工作线程,工作线程不能更新UI,因此工作线程通过Handler通知UI线程更新UI

Handler构造器分析

创建匿名Handler或者内部Handler的时候,IDE会提示内存泄露的风险,因为内部类持有外部类引用,修改为静态内部类即可

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

Handler内部几个重要的属性

        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;

通过构造函数对属性进行赋值。类属性的命名规则以小写字母m开头,命名的规范值得学习。
其他几个重载的构造函数功能类似,对类属性的赋值。

通过Handler发送消息

Handler有多个发送消息的方法,但最终都调用了

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

发送消息就是把消息插入到消息队列,该消息在消息队列的位置由该消息处理的时间when决定

    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,这点很重要,之后的消息处理会用到。最终是调用了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("MessageQueue", 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;
    }

首先检查了改msg的target属性是不是null,也就是是否设置了处理该msg的Handler,没有设置Handler就抛出异常,同一个msg不能进队列两次,否则抛出异常
通过了上边两项检查后,设置msg已使用,设置msg的处理事件,为msg的when属性赋值

msg.markInUse();
msg.when = when;

然后根据msg的when属性和Message队列的情况,将该msg插入到队列合适的位置

Handler消息的轮询处理

消息通过Handler的post和send方法加入了handler的消息队列MessageQueue,那么消息队列中的消息是如何被依次处理的呢?是通过Looper,Handler有两个重要的属性

final MessageQueue mQueue;
final Looper mLooper;

在上边构造函数的分析中,看到mQueue是如何被赋值的

mQueue = mLooper.mQueue;

即Handler的消息队列就是Looper的消息队列,因此消息的轮询处理是交给了Looper。一个Looper和一个线程绑定,要想使一个线程具备Looper的能力(轮询消息队列),需要在线程run方法开头调用

private static void prepare(boolean quitAllowed)

    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中通过ThreadLocal线程本地变量将Looper绑定到了调用prepare的线程。然后要想使线程具有轮询能力,需要在线程run方法末尾调用

public static void 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方法中通过死循环处理消息队列中的消息

for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            ...
            msg.target.dispatchMessage(msg);
            ...
        }

从消息队列中依次取出消息,然后调用msg的target属性的dispatchMessage方法。
而target是如何被赋值的呢?是在Handler调用post或者send发送消息的时候被赋值的,被赋值为发送此消息的handler

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        ...

因此消息的处理又回到了Handler线程,通过Handler的dispatchMessage方法回调处理消息

Handler处理消息

在Handler所在线程,通过类似责任链模式的方式,处理该消息

    /**
     * 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);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值