@Before public void setUp() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { getInstrumentation().getUiAutomation().executeShellCommand( "pm grant " + mActivityRule.getActivity().getPackageName() + " android.permission.READ_CONTACTS"); } mActivityRule.getActivity(); // Initialize to default preferences KissApplication.getApplication(mActivityRule.getActivity()).getDataHandler().clearHistory(); PreferenceManager.getDefaultSharedPreferences(mActivityRule.getActivity()).edit().clear().apply(); PreferenceManager.setDefaultValues(mActivityRule.getActivity(), R.xml.preferences, true); // Remove lock screen Runnable wakeUpDevice = new Runnable() { public void run() { mActivityRule.getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } }; mActivityRule.getActivity().runOnUiThread(wakeUpDevice); } }
private static void grantReal(UiAutomation automation, String permission) { try { String targetPackageName = InstrumentationRegistry.getTargetContext().getPackageName(); ParcelFileDescriptor pfn = automation.executeShellCommand("pm grant " + targetPackageName + " " + permission); pfn.close(); } catch (IOException e) { Log.w(TAG, e); } } }
private void grantPermission(Context context, String permission) { if (Build.VERSION.SDK_INT < 23) { return; } UiAutomation automation = Registry.getRegistry().instrumentation.getUiAutomation(); String command = String.format(Locale.ENGLISH, "pm grant %s %s", context.getPackageName(), permission); ParcelFileDescriptor pfd = automation.executeShellCommand(command); InputStream stream = new FileInputStream(pfd.getFileDescriptor()); try { byte[] buffer = new byte[1024]; while (stream.read(buffer) != -1) { // Consume stdout to ensure the command completes } } catch (IOException ignored) { } finally { try { stream.close(); } catch (IOException ignored) { } } }
/** * Safe way to remove granted permission to you app without app restart. */ public static void resetAllPermission() { // permissions handling only available since android marshmallow if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return; } InstrumentationRegistry.getInstrumentation().getUiAutomation().executeShellCommand("pm reset-permissions"); EspWait.forDelay(DELAY_FOR_COMMAND_EXECUTION); }
private static void grantWritePermissionsForScreenshots() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation(); String appPackage = getTargetContext().getPackageName(); instrumentation.getUiAutomation().executeShellCommand("pm grant " + appPackage + " android.permission.READ_EXTERNAL_STORAGE"); instrumentation.getUiAutomation().executeShellCommand("pm grant " + appPackage + " android.permission.WRITE_EXTERNAL_STORAGE"); } catch (Exception e) { throw new RuntimeException( "Exception while granting external storage access to application apk", e); } } }