9

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.

tpunt
  • 2,552
  • 1
  • 12
  • 18
Abhriya Roy
  • 1,338
  • 17
  • 23

1 Answers1

10

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);
CodeWalker
  • 2,281
  • 4
  • 23
  • 50
  • when I try to do this, it gives me "java.lang.RuntimeException: An error occurred while executing doInBackground()" at long downloadID = downloadManager.enqueue(request); – Abhriya Roy Sep 01 '16 at 12:25
  • @AbhriyaRoy , I can't understand why you need to use `enqueue` method under AsyncTask, I think the error is appearing from there. If you really need that 1.you can pass a `Activity` to the `AsyncTask`'s constructor then you can use `Activity.runOnUiThread` or 2. you can use `new Handler(Looper.getMainLooper).pose(Runnable...)` –  Oct 12 '17 at 09:39