当使用handler.post()及当新的主题() [英] When to use handler.post() & when to new Thread()
问题描述
我不知道什么时候使用 handler.post(可运行)
&放大器;当使用
新线程(可运行)。开始();
I'm wondering when to use handler.post(runnable)
& when to use
new Thread(runnable).start();
据中提到的开发商DOC:
It is mentioned in developers doc:
导致了Runnable r以被添加到消息队列。可运行 将到该处理器相连接的线程上运行。
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.
这是否意味着,如果在的onCreate
的活动
类我写的:
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 seperate thread or on the Activity's thread?
感谢您
推荐答案
您应该使用Handler.post(),只要你想在UI线程执行操作。
You should use Handler.post() whenever you want to do operations in the UI thread.
所以我们可以说,在回调(这是在单独的线程中运行),你想改变一个TextView的文字,你应该使用Handler.post()。 在Android中,正如在许多其他的UI框架,UI元素(部件)只能从主线程修改。
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.
编辑:比如长时间运行的任务
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();
当然,如果你要执行的任务是很长而且是有风险的用户可能会在此期间切换到一些其他应用程序,你应该考虑使用的Service 。
这篇关于当使用handler.post()及当新的主题()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!