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

 String path = Environment.getExternalStoragePublicDirectory(directory).getAbsolutePath() + subpath;
 Log.e("PATH", path);

我得到



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



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

最佳答案

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

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);

注意 对于 mContext.getSystemService
  • Activity = getSystemService();
  • fragment = getActivity.getSystemService();
  • 适配器= mContext.getSystemService(); //pass context in adapter

  • 更新

    由于 OP 想要检查文件是否存在
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
    if(file.exists()){//File Exists};
    

    10-07 19:01
    查看更多