无法找到DownloadManager下载的文件

时间:2017-10-05 10:30:05

标签: java android

我有一个应用程序可以下载一些音频文件,然后播放它们(使用MediaPlayer。

我使用DownloadManager下载文件:

DownloadManager downloadmanager = downloadManager = (DownloadManager) getApplication().getSystemService(Context.DOWNLOAD_SERVICE);

     long id =  downloadManager.enqueue(new DownloadManager.Request(uri)
            .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
                                    DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false)
            .setTitle(e.getValue().getName())
            .setDescription(getString(R.string.DOWNLOAD_MANAGER_TITLE))
            .setDestinationInExternalFilesDir(getApplication(),Environment.DIRECTORY_DOWNLOADS,fileName));

现在,我可以验证文件是否已下载且可播放。 但我需要在File中打开它们,然后将该文件传递给MediaPlayer。

我这样做:

    Uri fileUri = dlMgr.getUriForDownloadedFile(id);

        File mAudioFile =new File(fileUri.getPath());

        if(mAudioFile.exists(){
     mediaPlayer.setDataSource(mAudioFile.getAbsolutePath());
    }else
{
//the file does not exist <-- this is where i end
}

我使用uid将下载ID存储在SharedPreferences中,并使用downloadmanager删除文件downloadmanager.remove(id)这样可以正常工作并删除正确的文件。

我做错了什么?

由于

1 个答案:

答案 0 :(得分:1)

只需使用Uri作为getUriForDownloadedFile的数据源,而不是从Uri返回MediaPlayer的文件路径:

if(fileUri!=null){
  mediaPlayer.setDataSource(fileUri);
}else{
   // fileUri is null
}
相关问题