我的问题仅出在华硕Nexus 7 2013 上。所有其他设备,包括华硕Nexus 7 2012都可以正常使用
该设备有2个摄像机ID:0,1。
但我无法使用它们打开相机。
//...
try {
//cameraID: 0 or 1
camera = Camera.open(cameraID);
//...
} catch (Exception e) {
e.printStackTrace();
}
所以我得到了:
java.lang.RuntimeException: Fail to connect to camera service
android.hardware.Camera.<init>(Camera.java:495)
android.hardware.Camera.open(Camera.java:341)
答案 0 :(得分:0)
问题在于新的Android 6+功能:运行时请求权限。
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (!permissionRequestInProgress) {
permissionRequestInProgress = true;
new Handler().post(new Runnable() {
@Override
public void run() {
if (ContextCompat.checkSelfPermission(RootActivity.this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(RootActivity.this,
new String[]{Manifest.permission.CAMERA},
CAMERA_PERMISSION_REQUEST);
} else {
//we got it
}
}
});
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case CAMERA_PERMISSION_REQUEST:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
//we got it
} else {
// permission denied
}
permissionRequestInProgress = false;
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}