在之前的 android 版本中,为了使用摄像头硬件,足以在 android manifest 中声明适当的权限和用途,但由于出现了 Marshmallow 版本,因此不再足以运行该应用程序。因为还需要启用运行时权限。考虑使用类似的代码,并使其适合您的项目,因为它使您有机会检查和启用权限。
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
cameraPreview.initializeCamera();
} else {
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PERMISSION_REQUEST_CODE) {
cameraPreview.initializeCamera();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void requestCameraPermission() {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.CAMERA
},
PERMISSION_REQUEST_CODE);
}
public void requestPermissionWithRationale() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
Snackbar.make(findViewById(android.R.id.content), R.string.no_cam_permission, Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.snackbar_action_grant, new View.OnClickListener() {
@Override
public void onClick(View v) {
requestCameraPermission();
}
})
.show();
} else {
requestCameraPermission();
}
}