How to save pdf in scoped storage?

前端 未结 1 1987
闹比i
闹比i 2021-01-15 00:51

Before the introduction of scoped storage i was using Download Manager to download pdf in my app and get the pdf from getExternalStorageDirectory, but due to sc

1条回答
  •  借酒劲吻你
    2021-01-15 01:28

    You can use below code to download and save PDF using scoped storage. Here I am using Downloads directory. Don't forget to give required permissions.

    @RequiresApi(Build.VERSION_CODES.Q)
    fun downloadPdfWithMediaStore() {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val url =
                    URL("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf")
                val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                connection.doOutput = true
                connection.connect()
                val pdfInputStream: InputStream = connection.inputStream
    
                val values = ContentValues().apply {
                    put(MediaStore.Downloads.DISPLAY_NAME, "test")
                    put(MediaStore.Downloads.MIME_TYPE, "application/pdf")
                    put(MediaStore.Downloads.IS_PENDING, 1)
                }
    
                val resolver = context.contentResolver
    
                val collection =
                    MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
    
                val itemUri = resolver.insert(collection, values)
    
                if (itemUri != null) {
                    resolver.openFileDescriptor(itemUri, "w").use { parcelFileDescriptor ->
                        ParcelFileDescriptor.AutoCloseOutputStream(parcelFileDescriptor)
                            .write(pdfInputStream.readBytes())
                    }
                    values.clear()
                    values.put(MediaStore.Downloads.IS_PENDING, 0)
                    resolver.update(itemUri, values, null, null)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题