private PermissionAwareActivity getPermissionAwareActivity() { Activity activity = getCurrentActivity(); if (activity == null) { throw new IllegalStateException("Tried to use permissions API while not attached to an " + "Activity."); } else if (!(activity instanceof PermissionAwareActivity)) { throw new IllegalStateException("Tried to use permissions API but the host Activity doesn't" + " implement PermissionAwareActivity."); } return (PermissionAwareActivity) activity; }
/** * Request the given permission. successCallback is called with true if the permission had been * granted, false otherwise. For devices before Android M, this instead checks if the user has * the permission given or not. * See {@link Activity#checkSelfPermission}. */ @ReactMethod public void requestPermission(final String permission, final Promise promise) { Context context = getReactApplicationContext().getBaseContext(); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { promise.resolve(context.checkPermission(permission, Process.myPid(), Process.myUid()) == PackageManager.PERMISSION_GRANTED); return; } if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) { promise.resolve(true); return; } try { PermissionAwareActivity activity = getPermissionAwareActivity(); mCallbacks.put( mRequestCode, new Callback() { @Override public void invoke(Object... args) { promise.resolve(args[0].equals(PackageManager.PERMISSION_GRANTED)); } }); activity.requestPermissions(new String[]{permission}, mRequestCode, this); mRequestCode++; } catch (IllegalStateException e) { promise.reject(ERROR_INVALID_ACTIVITY, e); } }