Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel download in DownloadManager

I am trying to download images from an URL using the following code :-

public static void writeToDisk(Context context, @NonNull String imageUrl, @NonNull String downloadSubfolder) {
    Uri imageUri = Uri.parse(imageUrl);
    String fileName = imageUri.getPath();
    String downloadSubpath = downloadSubfolder + fileName;

    DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(imageUri);
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setDescription(imageUrl);
    request.allowScanningByMediaScanner();
    request.setDestinationUri(getDownloadDestination(downloadSubpath));

    downloadManager.enqueue(request);
}

I cant figure out how to cancel the download once it's started.

like image 671
Abhriya Roy Avatar asked Sep 01 '16 11:09

Abhriya Roy


1 Answers

Use the enqueue method the get the ID as in

long downloadID = downloadManager.enqueue(request);

And, then use the remove method passing the downloadID to it.

downloadManager.remove(downloadID);
like image 155
CodeWalker Avatar answered Nov 03 '22 05:11

CodeWalker