这是QR Code扫描仪应用程序的一部分。在应用程序的最开始,它要求获得摄像头许可,当我单击以允许时,应用程序没有响应。但从第二次开始,该应用即可正常运行。我认为错误可能在于检查权限。请帮助我找到错误。
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraSource.start(surfaceView.getHolder());
} else {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
答案 0 :(得分:1)
在授予/拒绝您的许可后,将有一个名为onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
的回调方法。
回调函数返回requestCode
,这是首先被调用的代码权限。
您需要检查的所有内容
requestCode
等于您要求的许可权
grandResult[]
数组不为空
grantResults[0]
等于PackageManager.PERMISSION_GRANTED
示例:
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST: { // here, MY_PERMISSIONS_REQUEST is the intended request code
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}