When to use handler.post() & when to new Thread()

断了今生、忘了曾经 提交于 2019-11-28 15:38:48
kamituel

You should use Handler.post() whenever you want to do operations in the UI thread.

So let's say in the callback (which is running in separate thread) you want to change a TextView's text, you should use Handler.post().

In Android, as in many other UI frameworks, UI elements (widgets) can be only modified from main thread.


Edit: the example of long-running tasks

mHandler = new Handler();

new Thread(new Runnable() {
  @Override
  public void run () {
    // Perform long-running task here
    // (like audio buffering).
    // you may want to update some progress
    // bar every second, so use handler:
    mHandler.post(new Runnable() {
     @Override
     public void run () {
       // make operation on UI - on example
       // on progress bar.
     }
    });
  }
}).start();

Of course, if the task you want to perform is really long and there is a risk that user might switch to some another app in the meantime, you should consider using a Service.

To answer you specific question:

Does this mean if in the onCreate of Activity class I write:

Handler handler = new Handler() hanlder.post(runnable); then, runnable will be called in a separate thread or on the Activity's thread?

No it won't be. The Runnable will be called on the Main Thread itself. Handler is simply used for posting a message to the thread to which it is attached (where its is created). It does not create a thread on its own. In your example, you created a Handler in the main Thread (that where Activity.OnCreate() is called) and hence any message posted on such a Handler will be run on the Main Thread only.

worked

Example is jacked:

mHandler = new Handler();
new Thread(new Runnable(){
  @Override
  public void run () {
    mHandler.post(new Runnable() {
     @Override
     public void run () {
       mUiView.setX(x);
     }
    });
  }
}).start();

Alternatively you can skip the handler and use the post method on the view directly:

new Thread(new Runnable(){
  @Override
  public void run () {
    mUiView.post(new Runnable() {
     @Override
     public void run () {
       mUiView.setX(x);
     }
    });
  }
}).start();

This is a good post that outlines the difference: What exactly does the post method do?

use handler.post() when you want to post the code (usually from background thread) to the main thread. Yea, POST,just like you, post a letter to someone. With the help of handler the code will be executed ASAP i.e. almost immediately.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!