在Android KitKat上,getContentLength()返回-1
我是Android新手,正在开发一个文件下载应用程序,其中有一个显示下载百分比的ProgressDialog。 我使用AsyncTask,下面是代码中的问题部分在Android KitKat上,getContentLength()返回-1,android,download,android-progressbar,Android,Download,Android Progressbar,我是Android新手,正在开发一个文件下载应用程序,其中有一个显示下载百分比的ProgressDialog。 我使用AsyncTask,下面是代码中的问题部分 protected String doInBackground(String... f_url){ int count; try { URL url = new URL(f_url[0]); URLConnection conn = url.o
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;
}
我的问题是,这段代码在AndroidAPI16(JB)上运行得非常好,但在API19(KitKat)上却不行。在KitKat设备上,进度条百分比不会更新(始终为0)。检查代码后,我发现conn.getContentLength()在KitKat上运行时返回-1。因此它无法更新进度。但当我在API 16(JB)上运行它时,它会返回正确的文件大小
有人能帮我解决这个问题吗
提前感谢。您读过Android 4.4中迁移到WebView的内容吗: 大宗报价 如果从应用程序的UI线程以外的任何线程调用WebView上的方法,可能会导致意外结果。例如,如果应用程序使用多个线程,则可以使用runOnUiThread()方法确保代码在UI线程上执行: })) 您可以尝试以下方法:
conn.setRequestProperty("Accept-Encoding", "identity");
很抱歉,刚才的评论。谢谢你的回答。:)
conn.setRequestProperty("Accept-Encoding", "identity");