Mic*_*ers 2 user-interface android handler thread-safety
所有:
我真的不是grok处理程序了.我认为下面的代码 - 修改,以便,而不是使用处理程序,直接访问UI小部件(进度条) - 将导致跨线程异常.但事实并非如此.所以,我的问题是,这段代码不应该崩溃吗?如果没有,那么我什么时候需要使用处理程序?
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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
626 次 |
| 最近记录: |