2

全部:

我真的不了解处理程序。我认为下面的代码——修改为直接访问 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);
                    }
                });
            }
4

1 回答 1

6

如今,ProgressBar具有允许setProgress()在后台线程上调用的逻辑。它会检查您所在的线程,并在需要时自行post()处理。Runnable您可以在源代码中看到这一点。

于 2013-01-08T17:41:47.347 回答