Downloader.cancelDownload() instead of using external Thread logic

This is needed so that downloads can be canceled from within an
IntentService. Since the Downloader classes do not have any Thread logic in
them, they shouldn't use Thread logic within them anyway.

This also removes the unused argument to AsyncDownloader.attemptCancel().
This commit is contained in:
Hans-Christoph Steiner
2016-03-29 19:19:09 +02:00
parent 74274d21b4
commit 591b23b5ab
6 changed files with 55 additions and 11 deletions

View File

@@ -6,8 +6,11 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class HttpDownloaderTest {
@@ -56,4 +59,38 @@ public class HttpDownloaderTest {
assertTrue(receivedProgress);
}
}
@Test
public void downloadThenCancel() throws IOException, InterruptedException {
final CountDownLatch latch = new CountDownLatch(5);
URL url = new URL("https://f-droid.org/repo/index.jar");
File destFile = File.createTempFile("dl-", "");
destFile.deleteOnExit(); // this probably does nothing, but maybe...
final HttpDownloader httpDownloader = new HttpDownloader(url, destFile, null);
httpDownloader.setListener(new Downloader.DownloaderProgressListener() {
@Override
public void sendProgress(URL sourceUrl, int bytesRead, int totalBytes) {
System.out.println("DownloaderProgressListener.sendProgress " + bytesRead + " / " + totalBytes);
receivedProgress = true;
latch.countDown();
}
});
new Thread(){
@Override
public void run() {
try {
httpDownloader.download();
fail();
} catch (IOException e) {
e.printStackTrace();
fail();
} catch (InterruptedException e) {
// success!
}
}
}.start();
latch.await(100, TimeUnit.SECONDS); // either 5 progress reports or 100 seconds
httpDownloader.cancelDownload();
assertTrue(receivedProgress);
}
}