如果您的目标是 Android 11 API,则无法直接访问文件路径,因为 API 30(Android R) 中有许多限制。由于在 Android 10(API 29)中引入了范围存储 API,存储现在分为范围存储(私有存储)和共享存储(公共存储)。范围存储是一种您只能访问在scoped storage directory(i.e.
/Android/data/中创建的文件的类型 or /Android/media/<your-package-name>
。您无法从共享存储(即内部存储/外部 SD 卡存储等)访问文件
共享存储再次进一步分为媒体和下载集合。媒体集合存储图像、音频和视频文件。下载集合将处理非媒体文件。
要了解有关范围存储和共享存储的更多详细信息,请参阅此链接:Android 10 和 Android 11 中的范围存储。
如果您正在处理媒体文件(即图像、视频、音频),您可以使用支持 API 30(Android 11)的媒体商店 API 获取文件路径。如果您正在处理非媒体文件(即文档和其他文件),您可以使用文件 Uri 获取文件路径。
注意:如果您使用文件或 Uri util 类(如 RealPathUtil、FilePathUtils 等)来获取文件路径,此处可以获取所需的文件路径但无法读取该文件,因为它会抛出Read异常在 Android 11 中访问(权限被拒绝),因为您无法读取其他应用程序创建的文件。
所以要在Android 11(API 30) 中实现这种获取文件路径的场景,建议使用File Uri 将文件复制到应用程序的缓存目录中,并从缓存目录中获取文件访问的路径。
在我的场景中,我使用这两个 API 来获取 Android 11 中的文件访问权限。为了获取媒体文件(即图像、视频、音频)的文件路径,我使用了 Media Store API(请参阅此链接:Media Store API 示例 - 从共享存储访问媒体文件),以及获取非媒体文件(即文档和其他文件)的文件路径,我使用了 fileDescriptor。
文件描述符示例:我创建了系统对话框文件选择器来选择文件。
private fun openDocumentAction() {
val mimetypes = arrayOf(
"application/*", //"audio/*",
"font/*", //"image/*",
"message/*",
"model/*",
"multipart/*",
"text/*"
)
// you can customize the mime types as per your choice.
// Choose a directory using the system's file picker.
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
//type = "application/pdf" //only pdf files
type = "*/*"
putExtra(Intent.EXTRA_MIME_TYPES, mimetypes)
addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when it loads.
//putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
}
startActivityForResult(intent, RC_SAF_NON_MEDIA)
}
并在活动的onActivityResult方法中处理文件选择器的结果。在此处获取文件 URI。
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
RC_SAF_NON_MEDIA -> {
//document selection by SAF(Storage Access Framework) for Android 11
if (resultCode == RESULT_OK) {
// The result data contains a URI for the document or directory that
// the user selected.
data?.data?.also { uri ->
//Permission needed if you want to retain access even after reboot
contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
// Perform operations on the document using its URI.
val path = makeFileCopyInCacheDir(uri)
Log.e(localClassName, "onActivityResult: path ${path.toString()} ")
}
}
}
}
}
将文件 URI 传递给以下方法以获取文件路径。此方法将在应用程序的缓存目录中创建一个文件对象,并且您可以从该位置轻松获得对该文件的读取访问权限。
private fun makeFileCopyInCacheDir(contentUri :Uri) : String? {
try {
val filePathColumn = arrayOf(
//Base File
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.TITLE,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DISPLAY_NAME,
//Normal File
MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.MIME_TYPE,
MediaStore.MediaColumns.DISPLAY_NAME
)
//val contentUri = FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.provider", File(mediaUrl))
val returnCursor = contentUri.let { contentResolver.query(it, filePathColumn, null, null, null) }
if (returnCursor!=null) {
returnCursor.moveToFirst()
val nameIndex = returnCursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)
val name = returnCursor.getString(nameIndex)
val file = File(cacheDir, name)
val inputStream = contentResolver.openInputStream(contentUri)
val outputStream = FileOutputStream(file)
var read = 0
val maxBufferSize = 1 * 1024 * 1024
val bytesAvailable = inputStream!!.available()
//int bufferSize = 1024;
val bufferSize = Math.min(bytesAvailable, maxBufferSize)
val buffers = ByteArray(bufferSize)
while (inputStream.read(buffers).also { read = it } != -1) {
outputStream.write(buffers, 0, read)
}
inputStream.close()
outputStream.close()
Log.e("File Path", "Path " + file.path)
Log.e("File Size", "Size " + file.length())
return file.absolutePath
}
} catch (ex: Exception) {
Log.e("Exception", ex.message!!)
}
return contentUri.let { UriPathUtils().getRealPathFromURI(this, it).toString() }
}
注意:您也可以使用此方法获取媒体文件(图像、视频、音频)和非媒体文件(文档和其他文件)的文件路径。只需要传递一个文件 Uri.