我从文件管理器中选择了文档(PDF,DOC,DOCX),并尝试从Uri获取路径。但是,我得到一个例外 (FileUriExposedException:通过Intent.getData()在应用程序之外公开)
我已经使用以下代码从URI获取文件路径。
fun getPathDOC(context: Context, uri: Uri): String? {
var uri = uri
val needToCheckUri = Build.VERSION.SDK_INT >= 19
var selection: String? = null
var selectionArgs: Array<String>? = null
// Uri is different in versions after KITKAT (Android 4.4), we need to
// deal with different Uris.
if (needToCheckUri && DocumentsContract.isDocumentUri(context.applicationContext, uri)) {
if (isExternalStorageDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
} else if (isDownloadsDocument(uri)) {
val id = DocumentsContract.getDocumentId(uri)
if (id != null && id.startsWith("raw:")) {
return id.substring(4)
}
val contentUriPrefixesToTry = arrayOf(
"content://downloads/public_downloads",
"content://downloads/my_downloads",
"content://downloads/all_downloads"
)
for (contentUriPrefix in contentUriPrefixesToTry) {
val contentUri =
ContentUris.withAppendedId(Uri.parse(contentUriPrefix), java.lang.Long.valueOf(id!!))
try {
val path = getDataColumn(context, contentUri, null, null)
if (path != null) {
return path
}
} catch (e: Exception) {
}
}
} else if (isMediaDocument(uri)) {
val docId = DocumentsContract.getDocumentId(uri)
val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val type = split[0]
if ("image" == type) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
} else if ("video" == type) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
} else if ("audio" == type) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
}
selection = "_id=?"
selectionArgs = arrayOf(split[1])
}
}
if ("content".equals(uri.scheme!!, ignoreCase = true)) {
val projection = arrayOf(MediaStore.Images.Media.DATA)
var cursor: Cursor? = null
try {
cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, null)
val column_index = cursor!!.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
if (cursor.moveToFirst()) {
return cursor.getString(column_index)
}
} catch (e: Exception) {
println(e)
}
} else if ("file".equals(uri.scheme!!, ignoreCase = true)) {
return uri.path
}
return null
}
我尝试过:
How to get the file path from a URI that points to a PDF document?
https://www.dev2qa.com/how-to-get-real-file-path-from-android-uri/
我上面的代码在某些设备上运行,并且在某些设备上出现错误,请帮忙。