[英]Accessing UI view in another thread does *not* cause a crash. Why?
All: 所有:
I really don't grok handlers yet. 我真的还不讨厌处理程序。 I thought that the code below -- modified so that, instead of using a handler, the UI widget (progress bar) was accessed directly -- would cause a cross-threading exception. 我认为下面的代码(经过修改,以便直接使用UI小部件(进度条)而不是使用处理程序)将导致跨线程异常。 But it doesn't. 但事实并非如此。 So, my question is, shouldn't this code crash? 所以,我的问题是,这段代码是否应该崩溃? And if it doesn't, then when do I need to use a handler? 如果没有,那么我什么时候需要使用处理程序?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = 0;
progressBar = (ProgressBar) findViewById(R.id.progressbar);
progressBar.setMax(200);
//---do some work in background thread---
new Thread(new Runnable()
{
public void run()
{
//ó-do some work hereó-
while (progressStatus < 200)
{
progressStatus = doSomeWork();
progressBar.setProgress(progressStatus); // not on UI thread
//ó-Update the progress baró- // so shouldn't it crash?
// handler.post(new Runnable()
// {
// public void run() {
// progressBar.setProgress(progressStatus);
// }
// });
}
//---hides the progress bar---
handler.post(new Runnable()
{
public void run()
{
//---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---
progressBar.setVisibility(View.GONE);
}
});
}
Nowadays, ProgressBar
has logic that allows setProgress()
to be called on a background thread. 如今, ProgressBar
具有允许在后台线程上调用setProgress()
逻辑。 It checks to see what thread you are on and does its own post()
of a Runnable
if needed. 它检查看您在哪个线程上,并在需要时对Runnable
执行自己的post()
。 You can see this in the source code . 您可以在源代码中看到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.