Grant Uri Permissions

PHOTO EMBED

Sun Jul 31 2022 13:42:32 GMT+0000 (UTC)

Saved by @kamrantariq_123 #mvvm #kotlin

package com.scopedstoragepractice

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.storage.StorageManager
import android.provider.DocumentsContract
import android.util.Log
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.documentfile.provider.DocumentFile
import com.scopedstoragepractice.Constants.TAG
import com.scopedstoragepractice.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {

    lateinit var targetPath: String
    lateinit var binding: ActivityMainBinding
    var isLocationGranted: Boolean = false
    var isReadGranted: Boolean = false
    var isAudioGranted: Boolean = false
    lateinit var mPermissionLauncher: ActivityResultLauncher<Array<String>>
    lateinit var mWhatsLauncher: ActivityResultLauncher<Intent>
    lateinit var mWhatsLauncherStatus: ActivityResultLauncher<Intent>
    lateinit var whatsappStatus: String;


    @RequiresApi(Build.VERSION_CODES.Q)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater);
        setContentView(binding.root)


//        mPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()){ permissions->
//            isLocationGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: isLocationGranted
//            isReadGranted = permissions[Manifest.permission.READ_EXTERNAL_STORAGE] ?: isReadGranted
//            isAudioGranted = permissions[Manifest.permission.RECORD_AUDIO] ?: isAudioGranted
//        }
//
//        requestPermission()


        mWhatsLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback {
                if (it?.data != null) {
                    val treeUri = it.data!!.data
                    if (treeUri != null){
                        grantUriPermission(this.packageName,treeUri,Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                    //    contentResolver.takePersistableUriPermission(treeUri,Intent.FLAG_GRANT_READ_URI_PERMISSION)
                        getSharedPreferences("MY_PREFS", MODE_PRIVATE).edit().putString("DATA_PATH",
                            treeUri.toString()
                        ).apply()
                    }
                }
            })
        mWhatsLauncherStatus = registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback {
                if (it?.data != null) {
                    Log.e(TAG, "onCreate: " + it.data!!.data)
                    binding.whatsAppImage.setImageURI(it.data!!.data)
                }
            })

        binding.btnWhatsApp.setOnClickListener {
            val result = readfromprefs()
            if (result){
                val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
                    addCategory(Intent.CATEGORY_OPENABLE)
                    type = "image/* video/*"

                    // Optionally, specify a URI for the file that should appear in the
                    // system file picker when it loads.
                    putExtra(DocumentsContract.EXTRA_INITIAL_URI, Uri.parse(getSharedPreferences("MY_PREFS",
                        MODE_PRIVATE).getString("DATA_PATH","")))
                }
                mWhatsLauncherStatus.launch(intent)
            }else{
                getFolderPermission()
            }
        }


    }

    private fun readfromprefs(): Boolean {
        if (getSharedPreferences("MY_PREFS", MODE_PRIVATE).getString("DATA_PATH","").toString().isEmpty())
            return false
        else
            return true
    }

    @RequiresApi(Build.VERSION_CODES.Q)
    private fun getFolderPermission() {
        if (Build.VERSION.SDK_INT < 30) {
            // Less then 11
            targetPath =
                Environment.getExternalStorageDirectory().absolutePath + "/WhatsApp/Media/.Statuses"

        } else {
            // Android 11
            targetPath =
                Environment.getExternalStorageDirectory().absolutePath + "/Android/media/com.whatsapp/WhatsApp/Media/.Statuses"
        }
        val storageManager = application.getSystemService(Context.STORAGE_SERVICE) as StorageManager
        val intent = storageManager.primaryStorageVolume.createOpenDocumentTreeIntent()
        var uri = intent.getParcelableExtra<Uri>("android.provider.extra.INITIAL_URI") as Uri
        var scheme = uri.toString()
        scheme = scheme.replace("/root/", "/document/")
        scheme += "%3A$targetPath"
        uri = Uri.parse(scheme)
        intent.putExtra("android.provider.extra.INITIAL_URI", uri)
        intent.putExtra("andriod.content.extra.SHOW_ADVANCED", true)
        mWhatsLauncher.launch(intent)
    }


    private fun requestPermission() {

        isLocationGranted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
        isReadGranted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.READ_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
        isAudioGranted = ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED

        val permissionResuest: MutableList<String> = ArrayList()

        if (!isLocationGranted) {
            permissionResuest.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }

        if (!isReadGranted) {
            permissionResuest.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }

        if (!isAudioGranted) {
            permissionResuest.add(Manifest.permission.RECORD_AUDIO)
        }

        if (permissionResuest.isNotEmpty()) {
            mPermissionLauncher.launch(permissionResuest.toTypedArray())
        }


    }

}
content_copyCOPY