I'm developing an app that require some system permissions, however these are no longer granted automatically at installation time on Android Marshmallow.
I would like to request these permissions at runtime and run some kind of automation to grant them without needing a user to tap the 'allow' button when the System permissions Dialog appears.
How can I achieve this? Is there any way to do so in Marshmallow and later versions?
For Marshmallow or later permissions are not granted at install time and must be requested when required at runtime (if not granted previously.)
To do this, you need to run
ActivityCompat.requestPermissions()
to pop up the systems permissions dialog in your Activity, at the time when the user is undertaking an action that requires additional system permissions.An example of this for the
WRITE_EXTERNAL_STORAGE
permission would be:Note:
WRITE_EXTERNAL_STORAGE_REQUEST_CODE
is an arbitrary integer constant you should define elsewhere.The permissions you request should also be declared in your
AndroidManifest.xml
. In this example the declaration would be:In order to handle the system permissions dialog response you will also need to implement
onRequestPermissionsResult()
in your Activity. For this example the code would be similar toIf you are automating your app through Espresso, UIAutomator and/or some other UI testing framework you will need to anticipate and click the system dialog during your test, which can be accomplished with the following test code:
A more comprehensive explanation of testing System UI Permissions is available here.