android - 从存储中选择一个 pdf 并使用 pdf 应用程序打开它
问题描述
我喜欢从存储中选择一个 pdf 文件。之后,它应该使用用户选择的 pdf 阅读器应用程序打开选择的 pdf 文件。我可以选择一个文件,但之后应用程序崩溃并抛出:
android.content.ActivityNotFoundException: No Activity found to handle Intent
我试过了:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_menu)
btnTravels.setOnClickListener {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
//val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "application/pdf"
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
startActivityForResult(intent, R.integer.request_code_pdf)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if (requestCode == R.integer.request_code_pdf) {
if (data != null) {
Log.i("gotresult", data.data.toString())
data.data?.also {uri ->
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(uri,"document/pdf")
intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
startActivity(intent)
}
}
}
}
}
Log.i 向我展示了这一点。它看起来并不像文件名:
content://com.android.providers.downloads.documents/document/msf%3A462052
解决方案
Replace:
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(uri,"document/pdf")
intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
startActivity(intent)
with:
val intent = Intent(Intent.ACTION_VIEW, uri)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
startActivity(intent)
document/pdf
is not a valid MIME type, and you need to grant permission to the viewer app to read the content.
Also, remove intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
, since you are not handling multiple documents.
It doesn't really look like a Filename
It is not supposed to be a filename. It is supposed to be a Uri
pointing to a document that the user selected via ACTION_OPEN_DOCUMENT
.
推荐阅读
- windows - Makefile 未设置 GOOS 环境变量
- html - Boostrap 4:在一个
- java - 休息模板 - 如何在发送原始 POST 请求字符串之前检索它
- django - 如何使用模式作为 Django JSONField 的默认值
- android-management-api - 在什么情况下,设备的状态会变为禁用或删除
- python - DataFrame 的 Pandas 子集,每个类具有固定数量的值
- r - 在纵向数据中定义情节
- postgresql - 如何避免对默认列值进行多次更新?
- c++ - 创建不启动 cmd 窗口的 windows Qt 应用程序
- python - 如何正确使用 run_in_executor?