我通过Cordova插件(android)访问相机。为此,我向用户询问permission
。如果用户在permission
对话框中单击“允许”,则必须启动摄像头。为此,在原生android中,我重写了onRequestPermissionsResult
方法,如
@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;
}
}
所以,我想在Cordova插件中使用onRequestPermissionsResult
。任何人都可以帮助我吗?
答案 0 :(得分:3)
如果将该方法放在插件.java
文件中,它应该照常工作。关于运行时权限的主题甚至有很好的documentation。
请求权限如下:
cordova.requestPermission(CordovaPlugin plugin, int requestCode, String permission);
回调方法如下所示:
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) throws JSONException {
... // you can find the whole example implementation in the docs
}
如果你不想自己实现这个,你可以随时使用这个方便的插件:cordova-plugin-android-permissions来请求相机的许可。
编辑(如何使用android-permissions插件):
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
}
}
}
});