gpt4 book ai didi

android - 在 onActivityResult 中收到 "content://"Uri 后从 MediaStore 获取 PDF?

转载 作者:行者123 更新时间:2023-12-02 12:07:51 29 4
gpt4 key购买 nike

我开始 ACTION_GET_CONTENT为了选择 PDF 的 Intent :

override fun routeToFilePicker() {
val intent = Intent()
intent.type = MediaType.PDF.toString()
intent.action = Intent.ACTION_GET_CONTENT
activity.startActivityForResult(
Intent.createChooser(intent, "Select PDF"),
REQUEST_CODE_PDF_PICKER
)
}
然后在 onActivityResult我尝试从 Uri ( content//:path) 创建 PDF:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_PDF_PICKER ) {
data?.data?.let { pdfUri: Uri ->
val pdfFile: File = pdfUri.toFile() <-- chrash
...
}
}
}
pdfUri.toFile()导致致命异常:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1003, result=-1, data=Intent { dat=content://com.android.providers.downloads.documents/document/3569 flg=0x1 }} to activity {my.package.name.activity}: java.lang.IllegalArgumentException: Uri lacks 'file' scheme: content://com.android.providers.downloads.documents/document/3569

Caused by: java.lang.IllegalArgumentException: Uri lacks 'file' scheme: content://com.android.providers.downloads.documents/document/3569
我需要一个文件才能将页面转换为图像。
如何从 MediaStore 返回的 Uri 中获取 PDF 作为文件?

最佳答案

这就是我将 pdf 作为文件获取的方式:

val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
type = "application/pdf"
addCategory(Intent.CATEGORY_OPENABLE)
flags = flags or Intent.FLAG_GRANT_READ_URI_PERMISSION
}
startActivityForResult(intent, 111)
在您的 OnActivityResult(requestCode:Int,resultCode:Int,data:Intent?)
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
// 101 -> {
// data?.data?.also { uri ->
// Log.i(TAG, "Uri: $uri")
// baseAdapter?.add(ImageArray(null, null, uri.toString()))
// }
// }
111 -> {
data?.data?.also { documentUri ->
baseActivity.contentResolver?.takePersistableUriPermission(
documentUri,
Intent.FLAG_GRANT_READ_URI_PERMISSION
)
val file = DocumentUtils.getFile(baseActivity,documentUri)//use pdf as file
}
}
}

}
将 Uri 转换为文件的单例类:
object DocumentUtils {
fun getFile(mContext: BaseActivity?, documentUri: Uri): File {
val inputStream = mContext?.contentResolver?.openInputStream(documentUri)
var file = File("")
inputStream.use { input ->
file =
File(mContext?.cacheDir, System.currentTimeMillis().toString()+".pdf")
FileOutputStream(file).use { output ->
val buffer =
ByteArray(4 * 1024) // or other buffer size
var read: Int = -1
while (input?.read(buffer).also {
if (it != null) {
read = it
}
} != -1) {
output.write(buffer, 0, read)
}
output.flush()
}
}
return file
}
}
P.S:不要忘记在运行时询问权限
Manifest.permission.WRITE_EXTERNAL_STORAGE
Manifest.permission.READ_EXTERNAL_STORAGE

关于android - 在 onActivityResult 中收到 "content://"Uri 后从 MediaStore 获取 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60946366/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com