Sunday , November 28 2021

Android Request Permission at Runtime Example – Android Coding by DMTechnolab

class Main activity : AppCompatActivity()) {{

// step 1

// We need an example of InstResultLauncher first

Private Latite Where requestPermissionLauncher: Activity ResultLauncher<String>

@Suppress()“Settexty 18 N”)

Override enjoy Go ahead()saveInstanceState: BundleThe) {{

Super.Go ahead()saveInstanceState)

setContentView()R.Layout.activity_main)

// stage 2

// We’ll call and save the function register. ForActivityResult ()

// It takes ActivResultContracts.RequestPermission ()

// And inside the following lambda we will get a callback

// whenever the user allows or disallows

// with the help of boolean value inside the following lamb

// We can check if permission was granted or not

requestPermissionLauncher =

registerForActivityResult()ActivityResultContracts.request permission())) {{ Approved ->

text view.The text = If ()Approved) {{

“Storage allowed”

// here you can go with an action requiring permission

// Now I am only showing a normal string in TextView

} other {{

“Storage not allowed”

// Here you have to leave the functionality that needs permission

// because the user has denied permission

// You can ask permission again when the user will request the feature

// who needs this permission

}

}

switch.setOnClickListener {{

// On clicking the button we will request WRITE_EXTERNAL_STORAGE permission

// This is just for the instance you can request the permission you need

// step 3

// request permission

requestStoragePermission())

}

}

Private enjoy requestStoragePermission()){{

When {{

Context.com.checkSelfPermission()

this,

Android.Clearly.Permission.WRITE_EXTERNAL_Storage

) == package manager.permission granted -> {{

// has allowed

// You can go with the flow that requires permission here

}

shouldShowRequestPermissionRationale()Android.Clearly.Permission.WRITE_EXTERNAL_STORAGE) -> {{

// This case means that the user has previously denied permission

// So here we can display an explanation for the user

// this is why we really need this permission

showPermissionRequestExplanation()

Get up()R.Wire.Right_storage),

Get up()R.Wire.permission request)

) {{ requestPermissionLauncher.launch()Android.Clearly.Permission.WRITE_EXTERNAL_STORAGE) }

}

other -> {{

// everything is fine you can just request permission

requestPermissionLauncher.launch()Android.Clearly.Permission.WRITE_EXTERNAL_STORAGE)

}

}

}

}


Source link

About dmtechnolab

Check Also

Simplified Coding

Android Espresso Tutorial – Testing Fragment in Isolation – Android Coding by DMTechnolab

Welcome to another tutorial in the Android test series. And this post is called Android …

Leave a Reply

Your email address will not be published. Required fields are marked *