Android Java runOnUiThread()

前端 未结 2 984
鱼传尺愫
鱼传尺愫 2021-01-02 19:04

I have been messing around a bit with the runOnUiThread method. And if I simply make a method in my activity:

public void Test()
{
    runOnUiThread(new Runn         


        
相关标签:
2条回答
  • 2021-01-02 19:18

    This is the full body from Activity.runOnUiThread(Runnable):

    public final void runOnUiThread(Runnable action) {
        if (Thread.currentThread() != mUiThread) {
            mHandler.post(action);
        } else {
            action.run();
        }
    }
    

    The method body is still executed in your background thread, and mHandler of class android.os.Handler implements an internal queue for Runnables posted to it, so unless you're doing blocking work in the Runnable (which is a big no-no on the UI Thread) or calling this method upwards of a thousand times in a short period, you should not see any difference.

    Now, if you were calling Handler.postAtFrontOfQueue(Runnable), then there'd be an issue, because your Runnable is essentially "cutting in line". In this case, that would likely cause a stutter, because your Runnable is being executed instead of any UI updates that needed to take place (like scrolling).

    Note that you only need to run UI updates on the UI thread, like calling any methods on a View (thus the name "UI Thread" and why this method exists) or any operation where the documentation explicitly states that it needs to be run on the UI thread. Otherwise, if you're already on a background thread, there's no real reason to leave it.

    0 讨论(0)
  • 2021-01-02 19:23

    It's unlikely that it would cause any significant interruption to your UI process, but there's really no point in running it on the UI thread.

    If you are doing any significant amount of work, you should make sure that you do not do it on the UI thread.

    0 讨论(0)
提交回复
热议问题