I am currently working on an application that requires several "dangerous" permissions. So I tried adding "ask for permission" as required in Android Marshmallow(API Level 23), but couldn't find how to do it.
How can I ask for permission using new permission model in my app?
This structure I am using to check if my app has permission and than request if it does not have permission. So in my main code from where i want to check write following :
Module checkIfAlreadyhavePermission() is implemented as :
Module requestForSpecificPermission() is implemented as :
and Override in Activity :
Refer this link for more details : http://revisitingandroid.blogspot.in/2017/01/how-to-check-and-request-for-run-time.html
This code below works perfectly.I am explaining with the help of an example.
In my case i placed the permission checks separately in a util class and passed the specific permissions i need to check from the appropriate classes.This enabled to reuse the permission check util file in the whole application.
The below code part shows the function call.In this case am requesting
android.Manifest.permission.READ_EXTERNAL_STORAGE
permission.In the above case permission is checked if it is allowed the
onAttachPressed();
function is called else we check request permission.The below is the code present in the util class in my case
PermissionUtils
And after the request if you might want to call the function from
onRequestPermissionsResult
or else you will need to press the button again for the function call.So just call it from
onRequestPermissionsResult
My class for request runtime permissions in
Activity
orFragment
SAMPLE using here
It also help you show rationale or open Setting to enable permission after user denied a permission (with/without
Never ask again
) option easierUsing in
Activity
likeDemo project on Github
Simple way to ask permission by avoiding writing lots of code,
https://github.com/sachinvarma/EasyPermission
How to add :
How to ask permission:
Hoping it will be helpful for someone.
I have used this wrapper (Recommended) written by google developers. Its super easy to use.
https://github.com/googlesamples/easypermissions
Function dealing with checking and ask for permission if required
Happy coding :)
There is a good library that can be used in case permissions need to be asked when permission is needed by a background service. Although a limitation of library is that it can not be used to just determine whether permissions are currently given to the app or not. It always asks the user if app doesn't already have them.
Do give it a try as it makes life simpler: Android Permissions