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?
Open a Dialog using the code below:
Get the Activity result as below:
More info: https://developer.android.com/training/permissions/requesting.html
Android-M ie, API 23 introduced Runtime Permissions for reducing security flaws in android device, where users can now directly manage app permissions at runtime.so if the user denies a particular permission of your application you have to obtain it by asking the permission dialog that you mentioned in your query.
So check before action ie, check you have permission to access the resource link and if your application doesn't have that particular permission you can request the permission link and handle the the permissions request response like below.
So finally, It's a good practice to go through behavior changes if you are planning to work with new versions to avoid force closes :)
Permissions Best Practices.
You can go through the official sample app here.
Try this
This is the simplest way to ask for permission in Marshmallow version.
Note:- Don't forget to add this same permission in manifest file also
Second Method Code for checking the permission is granted or not?
And override the method
I'm using this as a base Fragment class. I only ask for permissions from a fragment, but you could refactor it and make a similar Activity version.
There are two key methods you should use:
hasPermissionOrWillAsk - Use this to see if a permission has been asked for and denies by a user who doesn't want to be asked again. This is useful for disabling UI when the user has given their final answer about NOT wanting a feature.
runNowOrAskForPermissionsFirst - Use this to run some code that requires permissions. If the user has already granted permission, the code will run immediately. Otherwise, the code will run later if the user grants permission. Or not at all. It's nice because you specify the code in one place.
Here's an example:
Happy to get feedback on this. Not that this specific example is a little simplified in that you also need to check to see if Location Services are enabled on the device. (That's different than permissions.) Also, it only supports one permission at a time, but would be simple to modify if you need it to support more than one at a time.
From Android Marshmallow(API 23) and above by default all dangerous permission ( as per official doc official doc) disabled. After installation when app open first time then you have to grant permission at Run Time.
I achieved this following way:
IN Your activity class:
Runtime Permission AnyWhere In ApplicationHere is Example
and call code like this :
you can find more Github