我想知道什么时候应该使用 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/