Progressbar没有更新线程android

时间:2011-12-31 12:29:29

标签: android progress-bar download

当我下载文件时,我希望进度条与此同步。但不是,我的代码是:

Thread thread = new Thread() {
            public void run() {
                try {
                    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                        //add the data in the buffer to the file in the file output stream (the file on the sd card
                        fileOutput.write(buffer, 0, bufferLength);
                        //add up the size so we know how much is downloaded
                        downloadedSize += bufferLength;
                        pbar.setProgress((downloadedSize/totalSize)*100);
                        pbar.refreshDrawableState();

                        Log.d("CURRENT:", "" + (downloadedSize/totalSize)*100);
                    }
                } catch (Exception ex) {

                }
            }
        };
        thread.start();

此外,我的catlog文件未更新。请帮助....

2 个答案:

答案 0 :(得分:1)

您无法从后台主题更新用户界面,使用AsyncTask因为Androiders称之为painless threading

Here is a nice Tutorial使用ProgressBar

使用AsyncTask

答案 1 :(得分:1)

不需要AsyncTask,在你的线程中使用MyActivity.this.runOnUiThread()。会做与AsyncTask相同的工作,但它会减少你重新编码所有东西的时间。 :)干杯