我读过这个话题
我在下载大文件时遇到问题,因为进度对话框不上传进度或下载后只上传一次并突然显示 100%。但是当我下载小文件时,一切都很好。
我认为问题可能在这里:
publishProgress((int)(total*100/fileLength));
我的代码:
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
String sdpath = Environment.getExternalStorageDirectory().getAbsolutePat();
File dir = new File(sdpath + "/Myfolder");
dir.mkdir();
OutputStream output = new FileOutputStream(dir.toString() + "/" + "myfilename");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total/fileLength)*100);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
}
我的文件大约 80 MB。