Snippets Collections
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())
        }


    }

}
//Kotlin Kapt plugin used for annotations
id 'kotlin-kapt'

// RoomDatabase Libraries

 def roomVersion = "2.4.0"
    implementation "androidx.room:room-runtime:$roomVersion"
    kapt "androidx.room:room-compiler:$roomVersion"
    implementation "androidx.room:room-ktx:$roomVersion"

// Coroutines
   implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.3"
   implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.3"

// LiveCycle and ViewModel
 def lifecycle_version = "2.2.0"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"


// Retrofit

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'



// for enabling view and databinding in android tag

buildFeatures{
        dataBinding true
    }

    viewBinding {
        enabled = true
    }
star

Sun Jul 31 2022 13:42:32 GMT+0000 (Coordinated Universal Time)

#mvvm #kotlin
star

Sat Jul 30 2022 07:39:53 GMT+0000 (Coordinated Universal Time)

#mvvm #kotlin

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension