如何使用下载管理器获取下载的文件路径

Rap*_*ael 4 android file path

我可以使用下载管理器从服务器下载视频。但是,当我使用以下代码记录路径时。

 String path = Environment.getExternalStoragePublicDirectory(directory).getAbsolutePath() + subpath;
 Log.e("PATH", path);
Run Code Online (Sandbox Code Playgroud)

我得到

12-15 13:29:36.787 22807-22807/com.ezyagric.extension.android E/PATH:/storage/sdcard0/EZYAGRIC/Soil Testing.mp4。

现在这与手机上的路径不同

/storage/sdcard0/Android/data/com.ezyagric.extension.android/files/EZYAGRIC/Crop Insurance.mp4

是什么带来了这种差异,如何才能获得手机中的路径?

Abh*_*ngh 9

用于在默认下载目录中下载文件的代码片段。

DownloadManager.Request dmr = new DownloadManager.Request(Uri.parse(url));

// If you know file name
String fileName = "filename.xyz"; 

//Alternative if you don't know filename
String fileName = URLUtil.guessFileName(url, null,MimeTypeMap.getFileExtensionFromUrl(url));

dmr.setTitle(fileName);
dmr.setDescription("Some descrition about file"); //optional
dmr.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
dmr.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
dmr.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
DownloadManager manager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(dmr);
Run Code Online (Sandbox Code Playgroud)

注意对于mContext.getSystemService

  • 活动= getSystemService();
  • 片段= getActivity.getSystemService();
  • 适配器= mContext.getSystemService(); //pass context in adapter

更新

由于 OP 想要检查文件是否存在

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName); 
if(file.exists()){//File Exists};
Run Code Online (Sandbox Code Playgroud)