Vajira Lasantha Vajira Lasantha - 1 year ago 116
Android Question

URLConnection.getContentLength() returns -1 on Android KitKat

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();

// 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()) {

// Output stream to write file
OutputStream output = new FileOutputStream(apkPath);

byte data[] = new byte[1024];

long total = 0;

while ((count = != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// writing data to file
output.write(data, 0, count);

// flushing output

// closing streams

} 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.

Answer Source

Have you read Migrating to WebView in Android 4.4:

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() {
public void run() {
    // Code for WebView goes here


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download