Welcome back to another post, In this post, I am going to explain, how to ask runtime permission to use resources in android phones, and handle the various situations that might arise during this process. This Article is written to support the YouTube Tutorial video that I have uploaded on my channel, and I will try to explain the code that I have used in the video. So if you haven’t watched that video go on and watch it first and if you don’t understand or need Source code, you can get it all from the article.
Watch YouTube Video Tutorial Here :
Let’s get started.
The following code is used to check if the permission is already given to our app or not.
If the required permission is not given to our app, we need to ask for permission in run time from the user. The following code is used to ask for permission for specified resources in the android app.
Showing Alert Dialog With Yes/No Action Button:
While asking for permission at run time, the user has the option to either accept or deny it, so we need to handle both conditions in our application.
It is straight forward when the user gives permission but if the user denies it we will show some extra info to the user because if our app doesn’t get the permission it required, it may crash or behave differently, which we need to inform to the user. so it’s important to track the interaction of the user.
If user Deny the Permission we will create a new AlertDialog and Display that to the user with some extra information. Our Alert Dialog will have a title, message, and Two-button with Yes and No Options.
if the user select Yes we will recall the requestPermission() method. The Following Code creates the AlertDialog.
Now The MainActivity.java Looks like this.
You can Download Full Source Code for Ask Runtime Permission from GitHub Here.