簡體   English   中英

Android-下載文件時顯示進度條

[英]Android - Displaying a progress bar while downloading a file

我需要協助。 我一直在尋找試圖解決我的問題的方法的日子。 我想在Android中下載文件時顯示進度欄。 我找到了足夠的資源來下載文件,但一直在努力弄清楚如何顯示進度條。

這是我的下載代碼:

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

使用asynctask。 在線上有許多教程可以幫助您准確地進行嘗試。

您是否嘗試閱讀AsyncTask文檔 該示例正是您要嘗試執行的操作。 該示例使用publishProgress()onProgressUpdate()

OnPreExecute()上設置進度條,定期調用publishProgress() ,並在onProgressUpdate()更新進度條。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM