我的文件下载时,setProgress方法不会更新ProgressBar

时间:2017-09-27 02:58:39

标签: android android-progressbar

  1. 下载文件的代码:

    Dialog dialog;
    int totalSize = 0;
    ProgressBar mProgressBar;
    int downloadedSize = 0;
    
    public void downloadFile(){
        try {
            URL url = new URL("http://.../my_file.mp3");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
    
            urlConnection.connect();
    
            File SDCardRoot = Environment.getExternalStorageDirectory();
    
            File dir = new File(SDCardRoot.getAbsolutePath(), "/dossier1/dossier2";
            dir.mkdirs();
    
            File file = new File(dir, "my_file.mp3");
    
            FileOutputStream fileOutput = new FileOutputStream(file);
    
            InputStream inputStream = urlConnection.getInputStream();
    
            totalSize = urlConnection.getContentLength();
    
            runOnUiThread(new Runnable() {
                public void run() {
                    mProgressBar.setMax(totalSize);
                }
            });
    
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
    
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
    
                runOnUiThread(new Runnable() {
                    public void run() {
                        mProgressBar.setProgress(downloadedSize);
                    }
                });
            }
    
            fileOutput.close();
    
            runOnUiThread(new Runnable() {
                public void run() {
                    //mProgressBar.dismiss();
                }
            });
    
        } catch (final MalformedURLException e) {
            showError("Error : MalformedURLException " + e);
            e.printStackTrace();
        } catch (final IOException e) {
            showError("Error : IOException " + e);
            e.printStackTrace();
        }
        catch (final Exception e) {
            showError("Error : Please check your internet connection " + e);
        }
    }
    
  2. showProgress方法:

    public  void showProgress(){
    dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.myprogressdialog);
    dialog.setTitle("Download Progress");
    
    TextView text = (TextView) dialog.findViewById(R.id.tv1);
    text.setText("Downloading...");
    cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    cur_val.setText("Starting download...");
    dialog.show();
    
    mProgressBar = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    mProgressBar.setProgress(0);
    mProgressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.blue_progress));
    }
    
  3. mProgressDialog的布局(res / layout中的myprogressdialog.xml):

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/layout_root"
    android:orientation="vertical"
    android:padding="10dp">
    
    <TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#FFF"
    android:text="hello"
    android:textStyle="bold"
    />
    
    <ProgressBar
    android:id="@+id/progress_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:progress="0"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="10dp"
    style="?android:attr/progressBarStyleHorizontal"
    android:maxHeight="10dip"
    android:minHeight="10dip"
    />
    
    <TextView
    android:id="@+id/cur_pg_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#0F0"
    android:text="hello"
    android:layout_marginTop="5dp"
    android:textStyle="bold|italic"    />
    
    </LinearLayout>
    
  4. 用于为mProgressBar提供蓝色的Xml(res / drawable中的blue_progress.xml)

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient android:startColor="#ff9d9e9d"
            android:centerColor="#ff5a5d5a"
            android:centerY="0.75"
            android:endColor="#ff747674"
            android:angle="270"
            />
    </shape>
    </item>
    <item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners android:radius="5dip" />
            <gradient android:startColor="@android:color/holo_blue_bright"
                android:centerColor="@android:color/holo_blue_dark"
                android:centerY="0.75"
                android:endColor="@android:color/holo_blue_light"
                android:angle="270"
                />
        </shape>
    </clip>
    </item>
    </layer-list>
    
  5. 我的文件下载时,

    setProgress方法不会更新ProgressBar! 你能建议我解决吗?

1 个答案:

答案 0 :(得分:0)

https://developer.android.com/reference/android/os/AsyncTask.html

我建议阅读AsyncTask,因为有一些非常好的工具可以帮助你异步更新UI线程。
异步任务允许您在后台线程上运行任务,当它完成(或正在进行)时,为UI提供更新。通常这允许您跳过制作UI Runnables - 但这取决于您的情况。

反正 要覆盖的方法是AsyncTask中的onProgressUpdate。此外,它可能会为您在将来尝试实现这一目标带来一些麻烦。

祝你好运!希望有所帮助。