What's the difference between Activity.runOnUiThread(runnable action) and Handler.post()?

后端 未结 3 1278
终归单人心
终归单人心 2020-12-09 08:15

What\'s the differences/ advantages / drawbacks between using Activity.runOnUiThread or Handler.post(runnable action) in android ?

3条回答
  •  忘掉有多难
    2020-12-09 08:46

    Activity.runOnUiThread() is a special case of more generic Handlers. With Handler you can create your own event query within your own thread. Using Handlers instantiated with default constructor doesn't mean "code will run on UI thread" in general. By default, handlers binded to Thread from which they was instantiated from. To create Handler that is guaranteed to bind to UI (main) thread you should create Handlerobject binded to Main Looper like this:

    Handler mHandler = new Handler(Looper.getMainLooper());
    

    Moreover, if you check the implementation of runOnuiThread() method, it is using Handler to do the things:

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

    As you can see from code snippet above, Runnable action will be executed immediately, if runOnUiThread() is called from the UI thread. Otherwise, it will post it to the Handler, which will be executed at some point later.

提交回复
热议问题