Android - Displaying a progress bar while download

2019-02-11 01:44发布

I need some help. I have been searching for days trying to find solution to my problem. I would like to show a progress bar while downloading a file in Android. I found enough to download the file but have struggled to figure out how to display a progress bar.

Here is my download code:

            String sURL = getString(R.string.DOWNLOAD_URL) + getString(R.string.DATABASE_FILE_NAME);
        HttpClient  httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(sURL);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        Header[] clHeaders = response.getHeaders("Content-Length");
        Header header = clHeaders[0];
        int totalSize = Integer.parseInt(header.getValue());
        int downloadedSize = 0;
        if (entity != null) {
            InputStream stream = entity.getContent();
            byte buf[] = new byte[1024 * 1024];
            int numBytesRead;

            BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
            do {
                numBytesRead = stream.read(buf);
                if (numBytesRead > 0) {
                    fos.write(buf, 0, numBytesRead);
                    downloadedSize += numBytesRead;
                    //updateProgress(downloadedSize, totalSize);
                }
            } while (numBytesRead > 0);
            fos.flush();
            fos.close();
            stream.close();
            httpclient.getConnectionManager().shutdown();

2条回答
等我变得足够好
2楼-- · 2019-02-11 02:07

Have you tried reading the documentation for AsyncTask? The example there is exactly what you are trying to do. The example uses the method publishProgress() and onProgressUpdate().

Set up a progress bar on OnPreExecute(), call publishProgress() periodically, and update the progress bar in onProgressUpdate().

查看更多
Juvenile、少年°
3楼-- · 2019-02-11 02:13

Use an asynctask. There are dozens of tutorials online for exactly what you're trying to do.

查看更多
登录 后发表回答