android - 何时使用 handler.post() 以及何时使用 new Thread()

标签 android android-handler android-thread

我想知道什么时候应该使用 handler.post(runnable); 什么时候应该使用 new Thread(runnable).start();

在 Handler 的开发者文档中有提到:

Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

这是否意味着如果我写在 Activity 类的 onCreate() 中:

Handler handler = new Handler();
handler.post(runnable);

那么runnable会在单独的线程中调用还是在Activity的线程中调用?

最佳答案

当你想在 UI 线程上进行操作时,你应该使用 Handler.post()

假设您想在回调中更改 TextView 的文本。因为回调不在 UI 线程上运行,所以应该使用 Handler.post()

在 Android 中,与许多其他 UI 框架一样,UI 元素(小部件)只能从 UI 线程修改。

另请注意,术语“UI 线程”和“主线程”经常互换使用。


编辑:长时间运行任务的示例:

mHandler = new Handler();

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

当然,如果您要执行的任务真的很长,并且用户可能会在此期间切换到其他应用程序,您应该考虑使用 Service .

关于android - 何时使用 handler.post() 以及何时使用 new Thread(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15136199/

相关文章:

java - AudioManager 在死线程上向 Handler 发送消息?

java - 如果检测到互斥则停止当前线程

java - 单击 imageView 时如何显示项目

Android - Tamagotchi 游戏后台服务

android - 为什么使用 Messenger 而不是将引用传递给 Handler?

flutter - 如何解决flutter中的权限处理程序错误?

android - 线程错误

java - 旋转后用 ProgressBar 更新 ProgressDialog

android - 电子邮件 ContentResolver 的问题

android - 程序查询返回安全异常