-
-
Save ardock/2544687d6d95d79e7029d82146a21ce0 to your computer and use it in GitHub Desktop.
Tap the "allow" button while running an Android instrumental test using UIAutomator
This file contains hidden or 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
| package com.fewlaps.android.permissiongranter; | |
| import android.app.Activity; | |
| import android.content.pm.PackageManager; | |
| import android.os.Build; | |
| import android.support.test.uiautomator.UiDevice; | |
| import android.support.test.uiautomator.UiObject; | |
| import android.support.test.uiautomator.UiObjectNotFoundException; | |
| import android.support.test.uiautomator.UiSelector; | |
| import android.support.v4.content.ContextCompat; | |
| import static android.support.test.InstrumentationRegistry.getInstrumentation; | |
| public class PermissionGranter { | |
| 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(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(String permissionNeeded) { | |
| Context context = InstrumentationRegistry.getTargetContext(); | |
| 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