Android marshmallow request permission?
Open a Dialog using the code below:
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
Get the Activity result as below:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
More info: https://developer.android.com/training/permissions/requesting.html
Android Marshmallow: How to allow Runtime Permissions programatically?
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:
ActivityCompat.requestPermissions(
this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
WRITE_EXTERNAL_STORAGE_REQUEST_CODE
);
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:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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 to
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
if (grantResults.length == 0 || grantResults[0] == PackageManager.PERMISSION_DENIED) {
return; //permission not granted, could also optionally log an error
}
if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
//Do whatever you needed the write permissions for
}
}
If 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:
private void allowPermissionsIfNeeded() {
if (Build.VERSION.SDK_INT >= 23) {
UiObject allowPermissions = mDevice.findObject(new UiSelector().text("Allow"));
if (allowPermissions.exists()) {
try {
allowPermissions.click();
} catch (UiObjectNotFoundException e) {
Timber.e(e, "There is no permissions dialog to interact with ");
}
}
}
}
A more comprehensive explanation of testing System UI Permissions is available here.
How i can request permission at runtime in Android?
MY_PERMISSIONS_REQUEST_READ_CONTACTS is a static int variable that you need to set in your Activity. It is the request code that is used in onRequestPermissionsResult
. It is required so that you know which permission was acted upon (whether it be accepted or rejected) in onRequestPermissionsResult
.
At the top of your Activity just put private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;
(the number can be whatever you want)
When to request permission at runtime for Android Marshmallow 6.0?
In general, request needed permissions it as soon as you need them. This way you can inform the user why you need the permission and handle permission denies much easier.
Think of scenarios where the user revokes the permission while your app runs: If you request it at startup and never check it later this could lead to unexpected behaviour or exceptions.
How to request permissions on Android Marshmallow for JUnit tests
I found a solution to my problem. It was easy:
needs to create a new task in app-level build.gradle
file like this:
android.applicationVariants.all { variant ->
def applicationId = variant.applicationId
def adb = android.getAdbExe().toString()
def variantName = variant.name.capitalize()
def grantPermissionTask = tasks.create("create${variantName}Permissions") << {
println "Granting permissions"
"${adb} shell pm grant ${applicationId} android.permission.ACCESS_FINE_LOCATION".execute()
"${adb} shell pm grant ${applicationId} android.permission.WRITE_EXTERNAL_STORAGE".execute()
"${adb} shell pm grant ${applicationId} android.permission.READ_EXTERNAL_STORAGE".execute()
}
}
then add the following dependency:
preBuild.dependsOn "createDebugPermissions"
after that, all required permissions will be granted when you run any test
Related Topics
Auto Scale Textview Text to Fit Within Bounds
How Exactly Does the Android:Onclick Xml Attribute Differ from Setonclicklistener
How to Detect When an Android App Goes to the Background and Come Back to the Foreground
How to Draw a Path on a Map Using Kml File
Android, Detect When Other Apps Are Launched
Dexindexoverflowexception Only When Running Tests
Onsaveinstancestate () and Onrestoreinstancestate ()
Android Take Screenshot of Surface View Shows Black Screen
How to Send Device to Device Notification by Using Fcm Without Using Xmpp or Any Other Script.
How to Check the Current Status of the Gps Receiver
All Com.Android.Support Libraries Must Use the Exact Same Version Specification
Find Location of a Removable Sd Card
Error in Launching Avd With Amd Processor
Android: Check Whether the Phone Is Dual Sim