0

I am working with the Kotlin language in android studio. I am requesting permission to access the gallery and I am writing this when I use the "if-else" structure to query the permission and there is a dash above the requestPermissions statement. how do we solve this.

enter image description here

activity?.let {
        if (ContextCompat.checkSelfPermission(requireActivity().applicationContext,Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Emin
  • 179
  • 1
  • 10
  • Did you [read the requesting permission guide](https://developer.android.com/training/permissions/requesting#allow-system-manage-request-code)? – ianhanniballake Jan 10 '22 at 00:17
  • I could not do it – Emin Jan 10 '22 at 00:34
  • When a method name has a line through it like that, it means the method is deprecated. Technically it will still work, but you should use the newer approach. Take a look at the answers [here](https://stackoverflow.com/questions/66551781/android-onrequestpermissionsresult-is-deprecated-are-there-any-alternatives) – Tyler V Jan 10 '22 at 00:57
  • It's a feature of the IDE to tell you that the function is deprecated. Figure out the replacement. – code Jan 10 '22 at 22:30

1 Answers1

0

The new approach to request permissions is to use launchers. You have to create the launchers before setContent().

At the very top before onCreate, create a launcher property:

val storagePermissionLauncher = registerForActivityResult(ActivityResultContracts.startActivityForResult())
{ result->
  if(result.RESULT_CODE == RESULT_OK) {
    //permission granted
    doSomething()
  }
}

When you have to do something that requires a permission. You have to check if you have the permission:

if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
  //you have the permission
  doSomething()
}else{
//You don't have the permission, ask for it.
  storagePermissionLauncher.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE) 
}
Danish Ajaib
  • 83
  • 1
  • 3
  • 14