Android - displaying a progress bar when downloading a file

I need help. I searched for several days trying to find a solution to my problem. I want to show a progress bar when downloading a file on Android. I found enough to download the file, but struggled to figure out how to display the 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();
+3
source share
2 answers

Use asynthesis. There are dozens of online tutorials for what you are trying to do.

+2
source

AsyncTask? : , . publishProgress() onProgressUpdate().

OnPreExecute(), publishProgress() onProgressUpdate().

0

Source: https://habr.com/ru/post/1773750/


All Articles