无法从安卓文档中获取正确的 uri 格式



我在尝试获取文档的 URI 时遇到错误。 "content://com.android.providers.downloads.documents/document/158" 这是我得到的 URI。我无法从此 URI 获取路径。在这里,我分享了我的代码。

RC_PICK_DOCUMENT -> {
when (resultCode) {
Activity.RESULT_OK ->
processDocument(data?.data)
}
}

在onActivityResult中处理此代码,

if (requestCode == Constants.RESULT_PICK_DOC
&& resultCode == Activity.RESULT_OK
) {
try {
if (data != null) {
val uri = data.data
// Here You get URI path
val path = FileUtils().getDocPath(activity!!, uri!!)?.toUri()?.path
}
} catch (e: Exception) {
e.printStackTrace()
}
}

这是 FileUtils 类中的 getDocPath(( 函数

class FileUtils {
fun getDocPath(context: Context, uri: Uri): String? {
var path: String? = null
val projection =
arrayOf(MediaStore.Files.FileColumns.DATA)
val cursor =
context.contentResolver.query(uri, projection, null, null, null)
if (cursor == null) {
path = uri.path
} else {
cursor.moveToFirst()
val column_index = cursor.getColumnIndexOrThrow(projection[0])
path = cursor.getString(column_index)
cursor.close()
}
return if (path == null || path.isEmpty()) uri.path else path
}
}

最新更新