【问题标题】:setProgress method doesn't update the ProgressBar when my file is being downloaded下载我的文件时,setProgress 方法不会更新 ProgressBar
【发布时间】:2017-09-27 02:58:39
【问题描述】:
  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>
    

下载我的文件时,setProgress 方法不会更新 ProgressBar! 你能建议我任何解决方案吗?

【问题讨论】:

    标签: android android-progressbar


    【解决方案1】:

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

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

    无论如何, 您要覆盖的方法是 AsyncTask 中的 onProgressUpdate。此外,它可能会为您在将来尝试完成此任务时省去一些麻烦。

    祝你好运!希望有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多