Pregunta

I know how to disconnect a HTTPURLConnection with .disconnect() method. But how about URLConnection object? Myy app downloads a file with direct link from server via URLConnection.getInputStream. Download progress has a Stop button. I want to stop downloading when user touches Stop. thanks for answers.

¿Fue útil?

Solución

If you are using URLConnection.getInputStream(), then your downloading code might look like follows:

InputStream fileInputStream; // initialized 

// ...

byte[] buffer = new byte[1024 * 32];
int len;
int totalLen = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
    fstream.write(buffer, 0, len);
    totalLen += len;
}

so, to stop this download you should break this loop once some condition is true, one way is to use AtomicBoolean, since mostly you will set it in UI thread while downloading is in worker thread :

// in your download class
AtomicBoolean abort = new AtomicBoolean(false);

// Updated loop
while ((len = fileInputStream.read(buffer)) != -1) {
    if ( abort.get() ) {
       // do any necessary cleanup like closing streams
       break;
    }
    fstream.write(buffer, 0, len);
    totalLen += len;
}

then in your button click handler add: abort.set(true);

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top