0

As of Android 10 (Q) Storage Access Framework deprecated the way we originally saved documents to external Download folder, I'm trying to create a PDF document without asking Android Writing Storage permissions, prompting the user every time he needs to download it. But I can't figure out how to bring the PDF (in memory) directly to the creation Intent, without creating a File object (Uri), and missing the main point of not creating a file.

Here's my code:

private fun requestPDF() {
        val retrofit = Retrofit.Builder().baseUrl("foo")
            .build()
        val service = retrofit.create(PDFDownloadService::class.java)
        val call = service.get("bar")
        call.enqueue(object : Callback<ResponseBody> {
            override fun onResponse(
                call: Call<ResponseBody>,
                response: Response<ResponseBody>
            ) {
                if (response.isSuccessful) {
                    mPDF = response.body()!! // Complete PDF

                    DoAsync {
                        val uri = Uri.parse(mPDF.string()) // Code that I can't figure out

                        val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
                            data = uri
                            type = "application/pdf"
                            putExtra(Intent.EXTRA_TITLE, "My PDF file")
                            addCategory(Intent.CATEGORY_OPENABLE)
                        }

                        (parentContext as MainActivity).startActivityForResult(intent, WRITE_REQUEST_CODE)
                    }
                } else onFailure(call, Throwable("${response.code()}"))
            }

            override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
                Toast.makeText(
                    parentContext, "Error requesting PDF: ${t.message}",
                    Toast.LENGTH_LONG
                ).show()
            }
        })
    }

The PDF file is created but with 0Kb and unable to open.

Google I/O 19 about this topic: https://youtu.be/3EtBw5s9iRY?t=1582

Any suggestions on how to proceed would be appreciated!

4

0 回答 0