문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top