Android 异步UI

之前有分析过子线程中直接更新ui

众所周知CalledFromWrongThreadException是检查original thread,也就是创建ui的线程。那么在子线程中创建ui,自然也可以在此线程中更新ui。

要维护一个子线程,首先想到的就是HandlerThread

下面写个demo

class MainActivity : AppCompatActivity() {
    private val handlerThread = HandlerThread("AsyncHandlerThread")

    class H(looper: Looper, private val weak: WeakReference<MainActivity>) : Handler(looper) {
        var tvMain: TextView? = null

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                10086 -> {
                    val root = LayoutInflater.from(weak.get())
                        .inflate(R.layout.activity_main, null)
                    val wm: WindowManager =
                        weak.get()?.getSystemService(Context.WINDOW_SERVICE) as WindowManager
                    val param = WindowManager.LayoutParams()
                    param.width = WindowManager.LayoutParams.MATCH_PARENT
                    param.height = 300
                    wm.addView(root, param)
                    tvMain = root.findViewById(R.id.tvMain)
                    tvMain?.setOnClickListener {
                        tvMain?.text = "${Thread.currentThread()}"
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        handlerThread.start()
        val handler = H(handlerThread.looper, WeakReference(this@MainActivity))
        handler.sendEmptyMessage(10086)
    }

    override fun onDestroy() {
        handlerThread.quitSafely()
        super.onDestroy()
    }
}

Run,点击TextView验证一下



onClick回调在HandlerThread所在线程。通过这个思路,可以将部分ui挪到子线程中,减少主线程耗时。

追本溯源,WindowManager的实现类是WindowManagerImpl,

WindowManagerImpl.addView

    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow,
                mContext.getUserId());
    }

WindowManagerGlobal.addView

        ...
        ViewRootImpl root;
        root = new ViewRootImpl(view.getContext(), display);
        root.setView(view, wparams, panelParentView, userId);
        ...

ViewRootImpl构造方法中为mThread赋值、初始化Choreographer

        mThread = Thread.currentThread();
        mChoreographer = useSfChoreographer
                ? Choreographer.getSfInstance() : Choreographer.getInstance();

Choreographer.getSfInstance(),从ThreadLocal中取对应线程的Choreographer

    public static Choreographer getSfInstance() {
        return sSfThreadInstance.get();
    }

    private static final ThreadLocal<Choreographer> sSfThreadInstance =
            new ThreadLocal<Choreographer>() {
                @Override
                protected Choreographer initialValue() {
                    Looper looper = Looper.myLooper();
                    if (looper == null) {
                        throw new IllegalStateException("The current thread must have a looper!");
                    }
                    return new Choreographer(looper, VSYNC_SOURCE_SURFACE_FLINGER);
                }
            };

回看ViewRootImpl.setView()

        ...
        requestLayout();
        ...

ViewRootImpl.requestLayout()

    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

ViewRootImpl.scheduleTraversals()

    final ViewRootHandler mHandler = new ViewRootHandler();

    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

    final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }

mHandler调用Handler无参构造方法初始化取的是当前线程looper,如此一来mHandler、mChoreographer都在demo中HandlerThread线程所在的事件循环。

mTraversalRunnable

    final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }

doTraversal大家都懂,后面就是绘制流程了。

继续跟一下Choreographer相关逻辑,回看Choreographer.postCallback()

    public void postCallback(int callbackType, Runnable action, Object token) {
        postCallbackDelayed(callbackType, action, token, 0);
    }

    public void postCallbackDelayed(int callbackType,
            Runnable action, Object token, long delayMillis) {
        ...
        postCallbackDelayedInternal(callbackType, action, token, delayMillis);
    }

    private void postCallbackDelayedInternal(int callbackType,
            Object action, Object token, long delayMillis) {
        synchronized (mLock) {
            final long now = SystemClock.uptimeMillis();
            final long dueTime = now + delayMillis;
            mCallbackQueues[callbackType].addCallbackLocked(dueTime, action, token);

            if (dueTime <= now) {
                scheduleFrameLocked(now);
            } else {
                Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action);
                msg.arg1 = callbackType;
                msg.setAsynchronous(true);
                mHandler.sendMessageAtTime(msg, dueTime);
            }
        }
    }

Choreographer.scheduleFrameLocked()

    private void scheduleFrameLocked(long now) {
        if (!mFrameScheduled) {
            mFrameScheduled = true;
            if (USE_VSYNC) {
                // If running on the Looper thread, then schedule the vsync immediately,
                // otherwise post a message to schedule the vsync from the UI thread
                // as soon as possible.
                if (isRunningOnLooperThreadLocked()) {
                    scheduleVsyncLocked();
                } else {
                    Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_VSYNC);
                    msg.setAsynchronous(true);
                    mHandler.sendMessageAtFrontOfQueue(msg);
                }
            } else {
                Message msg = mHandler.obtainMessage(MSG_DO_FRAME);
                msg.setAsynchronous(true);
                mHandler.sendMessageAtTime(msg, nextFrameTime);
            }
        }
    }

到这里就差不太多。上述注释说明,在有Looper的线程立即发出vsync;否则post 一个带vsync的message到ui线程。我们的HandlerThread中当然是有Looper事件循环的啦。

Choreographer.scheduleVsyncLocked()

    private final FrameDisplayEventReceiver mDisplayEventReceiver;

    private final class FrameDisplayEventReceiver extends DisplayEventReceiver implements Runnable{}

    private void scheduleVsyncLocked() {
        mDisplayEventReceiver.scheduleVsync();
    }

调用父类DisplayEventReceiver.scheduleVsync()

    public void scheduleVsync() {
        if (mReceiverPtr == 0) {
            Log.w(TAG, "Attempted to schedule a vertical sync pulse but the display event "
                    + "receiver has already been disposed.");
        } else {
            nativeScheduleVsync(mReceiverPtr);
        }
    }

nativeScheduleVsync(),VSync信号最终调到C层。笔者比较懒,就不跟C层代码了,搜索一番得到结论,VSync信号接受回调的方法是onVsync()

FrameDisplayEventReceiver.onVsync()

        public void onVsync(long timestampNanos, long physicalDisplayId, int frame) {
            ...
            mTimestampNanos = timestampNanos;
            mFrame = frame;
            Message msg = Message.obtain(mHandler, this);
            msg.setAsynchronous(true);
            mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS);
        }

Message.obtain(mHandler, this),this也就是FrameDisplayEventReceiver这个Runnable,那么就调到了run方法。

FrameDisplayEventReceiver.run()

        public void run() {
            mHavePendingVsync = false;
            doFrame(mTimestampNanos, mFrame);
        }

doFrame()最终就是执行前面ViewRootImpl.mTraversalRunnable

验证一下,profile运行record一次看调用栈。



绘制流程确实都在AsyncHandlerThread这个子线程中了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • title: '深入理解android2-WMS,控件-图床版'date: 2020-03-08 16:22:42...
    刘佳阔阅读 920评论 0 0
  • 梳理流程和图形参考Stan_Z的博客:Android图形系统篇总结:https://www.jianshu.com...
    QGv阅读 2,595评论 0 1
  • 我是黑夜里大雨纷飞的人啊 1 “又到一年六月,有人笑有人哭,有人欢乐有人忧愁,有人惊喜有人失落,有的觉得收获满满有...
    陌忘宇阅读 8,471评论 28 53
  • 信任包括信任自己和信任他人 很多时候,很多事情,失败、遗憾、错过,源于不自信,不信任他人 觉得自己做不成,别人做不...
    吴氵晃阅读 6,132评论 4 8
  • 步骤:发微博01-导航栏内容 -> 发微博02-自定义TextView -> 发微博03-完善TextView和...
    dibadalu阅读 3,094评论 1 3