Ethan Shoe
Ethan Shoe

Reputation: 584

Android Download Manager "Download Unsuccessful"

This is my first time trying to implement DownloadManager and no matter what I try, I always get a notification saying "Download unsuccessful." I've looked at many other SO forums, a few tutorials, and what I have should work. Yes, I've set internet and external storage permissions in the manifest file. And yes, I've given storage permission in the app settings on the phone. I've tried this on both an Android emulator running API 28 and a real phone running the same. Here is the code I have:

        String url = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4";

        DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

        request.setTitle("title");

        request.setDescription("Your file is downloading");

        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC, "" + System.currentTimeMillis());

        request.allowScanningByMediaScanner();
        request.setAllowedOverMetered(true);
        request.setAllowedOverRoaming(true);

        //Enqueue download and save the referenceId
        long downloadReference = downloadManager.enqueue(request);

        if (downloadReference != 0) {
            Toast.makeText(getApplicationContext(), "download started", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(getApplicationContext(), "no download started", Toast.LENGTH_SHORT).show();
        }

Any help or suggestions are appreciated. Thanks.

Upvotes: 8

Views: 11345

Answers (2)

Ehsan
Ehsan

Reputation: 377

My Experience on 1/11/2021, min SDK 19, Target SDK 30

I spent a day on using Download Service and finally it worked. To sum it up for anyone who wants to try for the first time:

  1. Dont't forget to add WRITE_EXTERNAL_STORAGE and INTERNET permissions in Manifest.
  2. use requestPermissions() to grant permission from user.
  3. use getExternalFilesDir() instead of getExternalStorageDirectory().
  4. If you're downloading from http:// so add usesCleartextTraffic="true" to manifest.

Upvotes: 4

Abhay Koradiya
Abhay Koradiya

Reputation: 2117

This issue occur due to network security. If You are using un-secure url in above pie API, then it can't execute your url. Check Official Documentation.

Reason for avoiding cleartext traffic is the lack of confidentiality, authenticity, and protections against tampering; a network attacker can eavesdrop on transmitted data and also modify it without being detected.

Add following in manifest to bypass all security.

<application
  android:name=".ApplicationClass"
  ....
  android:usesCleartextTraffic="true">

Upvotes: 13

Related Questions