gpt4 book ai didi

android - URLConnection.getContentLength() 在 Android KitKat 上返回 -1

转载 作者:太空狗 更新时间:2023-10-29 15:26:50 26 4
gpt4 key购买 nike

我是 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) 上运行它时,它会返回正确的文件大小。

有人可以帮我解决这个问题吗?

提前谢谢你。

最佳答案

您是否阅读过在 Android 4.4 中迁移到 WebView:http://developer.android.com/guide/webapps/migrating.html

Blockquote If you call methods on WebView from any thread other than your app's UI thread, it can cause unexpected results. For example, if your app uses multiple threads, you can use the runOnUiThread() method to ensure your code executes on the UI thread:

runOnUiThread(new Runnable() {
@Override
public void run() {
// Code for WebView goes here
}

});

关于android - URLConnection.getContentLength() 在 Android KitKat 上返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22432969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com