Welcome back to another post, In this post i am going to explain, how to ask permission to use resources in android phone, and handle various situation that might arise during this process.
This Article is written to support the YouTube Tutorial video that i have uploaded in my channel, and i will try to explain the code that i have used in 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 article. Watch YouTube Video Tutorial Here :
Lets 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 the permission in run time from the user. The following code in used to ask for the permission for specified resources in android app.
Showing Alert Dialog With Yes/No Action Button:
While asking for for permission at run time , user have option to either accept or deny it, so we need to handle both condition in our application.
It is straight forward when user give the permission but if user deny it we will show some extra info to user because if our app don’t get the permission it required , it may crash or behave differently , that we need to inform to user. so its important to track the interaction of 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 title , message and Two button with Yes and No Options.
if user select Yes we will recall the requestPermission() method. The Following Code create the AlertDialog.
Now The MainActivity.java Look like this.
You can Download Full Source Code from GitHub Here.