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

3

我是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)上运行它时,它返回正确的文件大小。
请问有人能帮助我解决这个问题吗?
提前感谢您。
2个回答

1

你读过《在Android 4.4中迁移到WebView》吗:http://developer.android.com/guide/webapps/migrating.html

块引用 如果你从应用程序的UI线程以外的任何线程调用WebView的方法,可能会导致意想不到的结果。例如,如果你的应用程序使用多个线程,可以使用runOnUiThread()方法确保代码在UI线程上执行:

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

});


-2
你可以试试这个:
conn.setRequestProperty("Accept-Encoding", "identity");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接