1

User clicks to the button and the file browser opens. I need user to choose the pdf file only. According to the official documentation Because the user is involved in selecting the files or directories that your app can access, this doesn't require any system permissions. So, I did what I've been said. I added the REQUEST_EXTERNAL_STORAGE on my Manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

And I created a pdfPermissionListener using new Storage Access Framework:

       val pdfPermissionListener = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
   ) { isGranted ->
      if(isGranted) openFilePicker()
    }

when user clicks to the button I check the android version and either try to open the storage directly or ask for the permission as below:

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
      openFilePicker()
    } else {
    pdfPermissionListener.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
  }

My openFilePicker() method:

    fun openFilePicker() {
     val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
     intent.addCategory(Intent.CATEGORY.OPENABLE)
     intent.type = "application/pdf"
     intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
     signLauncher.launch(intent)
}

My result launcher:

    private val signlauncher = registerForActivityResult(
    ActivityResultContracts. startActivityForResult()
  ) { result ->
     when (result.resultCode) {
         Activity.RESULT_OK -> {
       //Take uri from result.data
     }

   Activity.RESULT_CANCELED -> {
    // show some Error 
  }

It works perfectly on below Android 13 devices. But nothing happens on Android 13. The file picker opens, user selects the correct pdf and returns to the app. But the result launcher doesn't seem to work. Neither RESULT_OK or RESULT_CANCELED. Nothing happens. I am not able to take the result.data.

I've tried everything, read every possible article and documentation but nothing helps. Now I'm thinking it is a possible Android issue. What can I do?

Aytaj
  • 67
  • 6
  • Please check this solution: https://stackoverflow.com/questions/72948052/android-13-read-external-storage-permission-still-usable#:~:text=From%20android%2010%20you%20can,SDK%2C%20less%20than%20android%2010. – Ammar Jun 06 '23 at 07:30

2 Answers2

0

Please try ComponentActivity instead of Activity. also you can extract data from getData(), please check below for example code.

Intent dataIntent = result.getData();
if (result.getResultCode() == ComponentActivity.RESULT_OK) {}
Akash kumar
  • 981
  • 3
  • 14
  • 27
0

Just use

val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
    // Handle Uri
     val safeUri = uri ?: run {
         println("not found")
     }

    println("found $safeUri")
}

getContent.launch("application/pdf")
Karim Karimov
  • 403
  • 1
  • 6
  • 14