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;
        }
    }

4

1 回答 1

3

使用此代码与executor service一起下载:

在 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"
于 2021-09-08T06:47:04.423 回答