Skip to content

Instantly share code, notes, and snippets.

@heitorcolangelo
Created September 9, 2016 01:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heitorcolangelo/3567cb17df26b60729fd9320e0b54e4d to your computer and use it in GitHub Desktop.
Save heitorcolangelo/3567cb17df26b60729fd9320e0b54e4d to your computer and use it in GitHub Desktop.
/**
* From: https://gist.github.com/rocboronat/65b1187a9fca9eabfebb5121d818a3c4
*/
public class PermissionUtils {
private static final int PERMISSIONS_DIALOG_DELAY = 3000;
private static final int GRANT_BUTTON_INDEX = 1;
public static void allowPermissionsIfNeeded(String permissionNeeded) {
try {
Context context = InstrumentationRegistry.getTargetContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !hasNeededPermission(context, permissionNeeded)) {
sleep(PERMISSIONS_DIALOG_DELAY);
UiDevice device = UiDevice.getInstance(getInstrumentation());
UiObject allowPermissions = device.findObject(new UiSelector()
.clickable(true)
.checkable(false)
.index(GRANT_BUTTON_INDEX));
if (allowPermissions.exists()) {
allowPermissions.click();
}
}
} catch (UiObjectNotFoundException e) {
System.out.println("There is no permissions dialog to interact with");
}
}
private static boolean hasNeededPermission(Context context, String permissionNeeded) {
int permissionStatus = ContextCompat.checkSelfPermission(context, permissionNeeded);
return permissionStatus == PackageManager.PERMISSION_GRANTED;
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
throw new RuntimeException("Cannot execute Thread.sleep()");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment