Question

I'm new to Android and developing a file downloading app with a ProgressDialog which shows the downloading percentage. I use AsyncTask and here is the trouble part of my code.

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;

    }

My issue is this code works really well on Android API 16 (JB) but not on API 19 (KitKat). On KitKat devices, the progress bar percentage does not update (always 0). After checking the codes, I found conn.getContentLength() returns -1 when I run it on KitKat. So it can not update the progress. But it returns correct file size when I run it on API 16 (JB).

Can somebody please help me to solve this?

Thank you in advance.

Was it helpful?

Solution

Have you read Migrating to WebView in Android 4.4: 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
}

});

OTHER TIPS

You can try this:

conn.setRequestProperty("Accept-Encoding", "identity");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top