开发者

Android - Displaying a progress bar while downloading a file

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();


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


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().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜