在具有Oreo及更高版本操作系统的Android设备中,如何从uri获取文件路径 [英] How to get the file path from uri in Android devices having Oreo and above OS
问题描述
要使用Intent选择音频文件,我正在使用此功能:-
To select an audio file using Intent , I am using this function :-
fun selectAudioFromStorage() {
val pictureActionIntent = Intent(Intent.ACTION_GET_CONTENT, null)
pictureActionIntent.type = "audio/*"
pictureActionIntent.putExtra("return-data", true)
startActivityForResult(pictureActionIntent, ResultConstants.RC_SELECT_AUDIO)
}
片段类的
onActivityResult提供这样的选定音频文件的Uri:
onActivityResult of the fragment class provides the Uri of the selected audio file like this :
content://com.android.providers.downloads.documents/document/raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Forganfinale.mp3
在Android(Lollipop)上,使用光标可以将uri转换为真实路径,但对于Oreo设备,我无法从此音频的Uri中获取真实路径.
On Android (Lollipop),To convert the uri to real path is working fine using cursor but for Oreo devices I am not able to get the real path from the Uri of this audio.
推荐答案
由于API 29及更高版本中的文件路径无法用于公共文件,我建议您不要尝试使用它们,而应使用Java FileDescriptor
As file paths are not usable in API 29 and above for public files I suggest that you don't try to use them but use a Java FileDescriptor
instead.
按照 https://developer.android.com/training/data -storage#scoped-storage
尤其是 https://developer. android.com/training/data-storage/shared/media#open-file-descriptor
许多API允许您提供FileDescriptor
而不是路径.
A lot of API's allow you to provide a FileDescriptor
instead of a path.
代替
要从URI中获取fileDescriptor
,请执行以下操作(在Java中)
To get a fileDescriptor
from a URI do the following (in Java)
ParcelFileDescriptor pfd =
this.getContentResolver().
openFileDescriptor(URI, "r");
FileDescriptor fileDescriptor = pfd.getFileDescriptor();
这篇关于在具有Oreo及更高版本操作系统的Android设备中,如何从uri获取文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!