How to ask for specific directory permission on Android 9 or below?

82 views Asked by At

I'm trying to ask directory specific permission on android 9 like we do for android 11 or above but it doesn't work for android 9 and opens recent directory when below "Method 1" gets called.

Does anyone knows if it's possible to ask directory specific permission on android 9 or below?

Below is the kotlin code that works for android 11 and above but not for android 9

//Method 1
fun openDirectory(){
        var pickerInitialPath = Environment.getExternalStorageDirectory().absolutePath

        pickerInitialPath += if(Build.VERSION.SDK_INT < 29){
            WS_DIR_OLDER_PATH    //"/WhatsApp/Media/.Statuses"
        }else{
            WS_DIRECTORY_PATH   //"/Android/media/com.whatsapp/WhatsApp/Media/.Statuses"
        }

        val folderUri = Uri.parse(pickerInitialPath)
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
            putExtra(DocumentsContract.EXTRA_INITIAL_URI, folderUri)
        }

        startActivityForResult(intent, 2000)

  }

//Method 2
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        try {
            if (requestCode == 2000
                && resultCode == Activity.RESULT_OK
            ) {
                data?.data?.also { uri ->

                    val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION
                    contentResolver.takePersistableUriPermission(uri, takeFlags)
                }
            }
        } catch (ex: Exception) {
            Log.d("OnActivity failure", "ON_ACTIVITY_RESULT FAILED WITH EXCEPTION\n$ex")
        }
    }

0

There are 0 answers