Search code examples
javaandroidandroid-download-manager

Why getUriForDownloadedFile() returns null


I am downloading the picture via DownloadManager (API 28). The picture is successfully downloaded and displayed in ImageView. I want find out the file name. But getUriForDownloadedFile() return null. Why?

private void dowloadfile() {
    Uri uri = Uri.parse(editText.getText().toString());
    DownloadManager.Request request = new DownloadManager.Request(uri);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
    request.setAllowedOverRoaming(false);
    request.setVisibleInDownloadsUi(true);
    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "picture." + extension);

    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    refid = downloadManager.enqueue(request);
    Uri u = downloadManager.getUriForDownloadedFile(refid);
}

Solution

  • after enqueue, the download is a asyn operation, the uri might be assigned after the download has finished, you need to listen to your receiver and pass the id to get the uri