Android

Storage Access Framework(SAF) 取得手機與雲端PDF檔

Storage Access Framework(SAF) 取得手機與雲端PDF檔

1.設置Intent 指定選取PDF

val PICK_PDF_REQUEST = 40
lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    binding.getData.setOnClickListener {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.type = "application/pdf"
        startActivityForResult(intent, PICK_PDF_REQUEST)
    }
}

2.取得回傳的檔案

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == PICK_PDF_REQUEST && resultCode == Activity.RESULT_OK) {

        var file: File? = null

        data?.data?.also { uri ->
            val cursor: Cursor? = contentResolver.query(uri, null, null, null, null)
            cursor?.run {
                if (moveToFirst()) {
                    val displayName: String =
                        getString(getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    try {
                        val `is`: InputStream? = contentResolver.openInputStream(uri)
                        val cache = File(externalCacheDir!!.absolutePath, displayName)
                        val fos = FileOutputStream(cache)
                        fos.write(`is`?.readBytes())
                        file = cache
                        fos.close()
                        `is`?.close()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
                close()
            }
        }

        binding.name.text = file?.name
        binding.path.text = file?.path
    }
}

3.效果展示

發表迴響