onRequestPermissionsResult in Cordova android plugin

Viewed 2280

I'm accessing the camera through Cordova plugin (android). For this, I'm asking permission to the user. If the user clicks "allow" in permission dialog I have to start the camera. For this, in native android, I'm overriding onRequestPermissionsResult method like

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case RequestCameraPermissionID: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                try {
                    cameraSource.start(surfaceView.getHolder());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        break;
    }
}

So, i want to use onRequestPermissionsResult in Cordova plugin. Can any one help me in this?

1 Answers

If you put that method in your plugins .java file it should work as usual. There is even good documentation on the topic of runtime permissions. Request the permission works like this:

cordova.requestPermission(CordovaPlugin plugin, int requestCode, String permission);

And the callback method looks like this:

public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
  ... // you can find the whole example implementation in the docs
}

If you don't want to implement this yourself you can always use this handy plugin: cordova-plugin-android-permissions to request the camera permission.

Edit (how to use the android-permissions plugin):

var permissions = cordova.plugins.permissions;

permissions.hasPermission(permissions.CAMERA, function(status) {
  if (status.hasPermission) {
    // here you can savely start your own plugin because you already have CAMERA permission
  }
  else {
    // need to request camera permission
    permissions.requestPermission(permissions.CAMERA, success, error);

    function error() {
      // camera permission not turned on
    }

    function success(status) {
      if (status.hasPermission) {
        // user accepted, here you can start your own plugin
      }
    }
  }
});
Related