Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the URI of a file that I downloaded with download manager?

Tags:

android

uri

I use download manager to download .ogg file. I use this code to download it:

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setDescription(list.get(position).getName());
            request.setTitle(list.get(position).getName());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            }
            request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, list.get(position).getName() + ".ogg");

            DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);

Now I want to share this file so I need his uri.

How can I get this file uri?

like image 711
G. Rajwan Avatar asked Oct 20 '25 02:10

G. Rajwan


1 Answers

Method DownloadManager.enqueue() returns an Id (DOC IS HERE). So, you must "store" that id for future operations (such as consult the Uri of the downloaded file).

This way, you can use that Id to get the Uri if the file was downloaded successfully using Uri getUriForDownloadedFile(long id); (DOC HERE)

EDIT

If you created a BroadcastReceiver to receive broadcasts about a completed download, you can get the Uri as soon as your file has been downlaoded:

private int mFileDownloadedId = -1;

// Requesting the download
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
mFileDownloadedId = manager.enqueue(request);

// Later, when you receive the broadcast about download completed.
private BroadcastReceiver onDownloadComplete = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
       long downloadedID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
       if (downloadedID == mFileDownloadedId) {
           // File received
           DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
           Uri uri = manager.getUriForDownloadedFile(mFileDownloadedId);
       }
    }
}

@Override
public void onResume() {
    super.onResume();

    registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

@Override
public void onPause() {
    super.onPause();
    // Don't forget to unregister the Broadcast
}
like image 158
W0rmH0le Avatar answered Oct 22 '25 17:10

W0rmH0le



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!