Created
September 9, 2016 01:51
-
-
Save heitorcolangelo/3567cb17df26b60729fd9320e0b54e4d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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