【发布时间】:2018-12-26 09:50:38
【问题描述】:
1.如下我的代码我已经更新了。
2. 每当我尝试从服务器下载数据时,我都会使用进度计数对话框,但下载开始时会显示计数百分比。
3. 但问题是计数仅显示高达 30%,当百分比达到 30% 时对话框将被关闭(这意味着所有数据下载成功)
4.但我需要显示对话框最多 100% 完成然后它应该被关闭.. 任何文件都有服务器它大约是 5 到 6 个文件。
@Override
protected void onPreExecute() {
this.progressDialog = new ProgressDialog(BaseApplication.getInstance().getCurrentActivity());
this.progressDialog.setMessage("Downloading Please wait.");
this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.progressDialog.setMax(100);
this.progressDialog.setCancelable(false);
this.progressDialog.show();
}
@Override
protected Boolean doInBackground(String... strings) {
// Here is my downloading code but i removed
DownloadData("" , "" , ""); //stuff
}
return true;
}
@Override
protected void onProgressUpdate(String... values) {
this.progressDialog.incrementProgressBy(5);
}
protected void onPostExecute(Boolean result) {
this.progressDialog.dismiss();
}
private void downloadData(String Folder, String Name, String URL) {
Log.i(TAG, "Coming to this downloadBookDetails ");
// int url1 = Integer.parseInt(pDownloadURL);
int len;
try {
// int urlsixe = pDownloadURL.length();
// Log.i(TAG, "URL lenght" + urlsixe);
URL url = new URL(URL);
Log.i(TAG, "pDownload URL" + url);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
ucon.connect();
int lenghtOfFile = ucon.getContentLength();
Log.i(TAG, "lenght of file" + lenghtOfFile);
InputStream is = ucon.getInputStream();
Log.i(TAG, " InputStream" + is);
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
Log.i(TAG, " BufferedInputStream" + inStream);
File directory = new File(pMainFolder, pFileName);
Log.i(TAG, "File Name dir" + directory);
FileOutputStream outStream = new FileOutputStream(directory);
byte[] buff = new byte[5 * 1024];
long total = 0;
while ((len = inStream.read(buff)) != -1) {
total += len;
// publishProgress("" + (int) ((total * 100) / urlsixe));
// Log.i(TAG, "Progress: Bar with Count " + (int) ((total * 100) / lenghtOfFile));
outStream.write(buff, 0, len);
}
publishProgress();
outStream.flush();
outStream.close();
inStream.close();
} catch (Exception e) {
//Add Network Error.
Log.i(TAG, "Download Error Exception " + e.getMessage());
e.printStackTrace();
}
}
【问题讨论】:
-
我认为 this.progressDialog.incrementProgressBy(5);不应硬编码为 5。它应根据下载的文件量计算百分比。
-
有什么理由增加 5?
-
只是测试目的,我把它设为 5,但当我把它设为 1 时它也不起作用
-
publishProgress() 是什么?无论如何,您应该使用有关读取字节数和文件长度的百分比。无论如何,您应该提高输入/输出关闭的鲁棒性。
-
我试过这个用一个进度条java / Android下载多个文件