Android basics: running code in the UI thread

后端 未结 7 532
悲&欢浪女
悲&欢浪女 2020-11-22 11:55

In the viewpoint of running code in the UI thread, is there any difference between:

MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
         


        
7条回答
  •  囚心锁ツ
    2020-11-22 12:24

    As of Android P you can use getMainExecutor():

    getMainExecutor().execute(new Runnable() {
      @Override public void run() {
        // Code will run on the main thread
      }
    });
    

    From the Android developer docs:

    Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).

    From the CommonsBlog:

    You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler.

提交回复
热议问题