首页 > 解决方案 > 从存储中选择一个 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

标签: androidkotlinpdfandroid-intent

解决方案


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.


推荐阅读