我正在尝试创建一个在片段中使用相机预览屏幕的应用程序。我决定将此代码作为起点,因为我需要将摄像头放在一个片段中:
运行应用程序时,我收到以下消息: D / CameraGuide:错误,相机无法打开
我认为这将意味着没有打开相机对象,但是代码确实说明了这一点。因此,我想了解为什么相机未打开时是否缺少我想要的东西。
这是我的权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus" />
这是来自GitHub的相关代码部分:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_camera_test, container, false);
requestPermission();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "Please provide Camera Permission to continue ", Toast.LENGTH_LONG).show();
}
// Create our Preview view and set it as the content of our activity.
boolean opened = safeCameraOpenInView(view);
if(opened == false){
Log.d("CameraGuide","Error, Camera failed to open");
return view;
}
// Trap the capture button.
Button captureButton = (Button) view.findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
private boolean safeCameraOpenInView(View view) {
boolean qOpened = false;
releaseCameraAndPreview();
mCamera = getCameraInstance();
mCameraView = view;
qOpened = (mCamera != null);
if(qOpened == true){
mPreview = new CameraPreview(getActivity().getBaseContext(), mCamera,view);
FrameLayout preview = (FrameLayout) view.findViewById(R.id.camera_preview);
preview.addView(mPreview);
mPreview.startCameraPreview();
}
return qOpened;
}
/**
* Safe method for getting a camera instance.
* @return
*/
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
e.printStackTrace();
}
return c; // returns null if camera is unavailable
}