我是Android新手,正在开发一个文件下载应用程序,并使用ProgressDialog来显示下载百分比。 我使用AsyncTask,这里是我的代码中的麻烦部分。
protected String doInBackground(String... f_url){
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conn = url.openConnection();
conn.connect();
// getting file length
int lenghtOfFile = conn.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File direct = new File(folder);
if(!direct.exists()) {
direct.mkdirs();
}
// Output stream to write file
OutputStream output = new FileOutputStream(apkPath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
我的问题是这段代码在Android API 16(JB)上运行得非常好,但在API 19(KitKat)上却不行。在KitKat设备上,进度条百分比不更新(始终为0)。检查代码后,我发现当我在KitKat上运行它时,conn.getContentLength()返回-1。因此,它无法更新进度。但是,当我在API 16(JB)上运行它时,它返回正确的文件大小。
请问有人能帮助我解决这个问题吗?
提前感谢您。