显示下载进度条

问题描述 投票:0回答:1

我在应用程序中使用执行程序服务从 URL 下载文件。我想添加一个水平进度条来显示下载进度,但我遇到了一些错误。如何在不使用异步任务的情况下在以下代码中添加进度条?

private class ExecutorServiceDownload implements Runnable {
    private String url;

    public ExecutorServiceDownload(String url) {
        this.url = url;
    }

    @Override
    public void run() {
        dlFile(url);
    }

    private String dlFile(String surl) {


        try {

            // I added progressbar here and it didn't download anything 

            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;

            URL url = new URL(surl);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
                return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage();

            input = connection.getInputStream();
            String title = URLUtil.guessFileName(String.valueOf(url), null, null);
            output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/test_files" + "/" + title);
            int contentLength = connection.getContentLength();

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        }
        return null;
    }
}
android download progress-bar executorservice android-threading
1个回答
3
投票

使用此代码通过执行器服务进行下载

在 onCreate 中:

ProgressBar progressBar;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreat`enter code here`e(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = findViewById(R.id.progressbar);

    
    downloading();

使用执行器服务下载文件:

private void downloading() {
progressBar.setVisibility(View.VISIBLE);


ExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Handler handler = new Handler(Looper.getMainLooper());

executor.execute(new Runnable() {

    int count;

    @Override
    public void run() {

        //Background work here
        try {

            // put your url.this is sample url.
            URL url = new URL("http://techslides.com/demos/sample-videos/small.mp4");
            URLConnection conection = url.openConnection();
            conection.connect();

      

            int lenghtOfFile = conection.getContentLength();

            // download the file

            InputStream input = conection.getInputStream();

            //catalogfile is your destenition folder
            OutputStream output = new FileOutputStream(catalogfile + "video.mp4");


            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....


                publishProgress(Integer.valueOf("" + (int) ((total * 100) / lenghtOfFile)));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();


            handler.post(new Runnable() {
                @Override
                public void run() {
                    //UI Thread work here
                    progressBar.setVisibility(View.GONE);

                }
            });
        } catch (Exception e) {

        }
    }
});

}

更新进度条

    private void publishProgress(Integer... progress) {

     progressBar.setProgress(progress[0]);

    }

和水平进度条的使用:

 <ProgressBar
    android:max="100"
    style="?android:attr/progressBarStyleHorizontal"
    android:visibility="invisible"
    android:id="@+id/progressbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
© www.soinside.com 2019 - 2024. All rights reserved.