android中四种更新UI的方法

来源:互联网 发布:非遗联盟大数据平台 编辑:程序博客网 时间:2024/06/11 17:25
1.activity的 runOnUiThread
源码如下:
public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }
2.view 的 post
源码如下:
public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }
        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().post(action);
        return true;
    }
3.handler 的 post
源码如下:
public final boolean post(Runnable r)
    {
       return  sendMessageDelayed(getPostMessage(r), 0);
    }
public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }
4.handler 的 sendMessage
源码如下:
 public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }

所有方法最终还是调用了handler的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);

}

关于这个方法,其实就是发送一个消息放入消息队列,然后looper会取出每个message并且交付给相应的handler做处理。也就是looper的loop方法,会调用handler的dispatchMessage方法,dispatchMessage调用handleMessage(msg)方法;

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;
...
        for (;;) {
            Message msg = queue.next(); // might block
          ...
            try {
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }

...
            msg.recycleUnchecked();
        }
    }

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

0 0