问题
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. 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);
}
});
}
回答1:
Nowadays, ProgressBar
has logic that allows setProgress()
to be called on a background thread. It checks to see what thread you are on and does its own post()
of a Runnable
if needed. You can see this in the source code.
来源:https://stackoverflow.com/questions/14220883/accessing-ui-view-in-another-thread-does-not-cause-a-crash-why