Android无法在曲面视图中切换到前置摄像头

时间:2017-01-30 12:03:15

标签: java android android-camera

我试图在表面视图中打开前置摄像头,但我得到的结果无法连接到摄像头服务

尝试过代码

    mCamera= Camera.open(cameraId);

0表示CAMERA_FACING_BACK

1 for CAMERA_FACING_FRONT

解决方案是什么??

2 个答案:

答案 0 :(得分:1)

是的,我得到了答案

    reverseCamera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean hasFront = hasFrontCamera();
            if (hasFront) {
                reverseCamera.setVisibility(View.VISIBLE);
                mCamera.stopPreview();
                mCamera.release();

                if (currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
                } else {
                    currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
                }
                mCamera = Camera.open(currentCameraId);

                setCameraDisplayOrientation(MainActivity.this, currentCameraId, mCamera);
                try {

                    mCamera.setPreviewDisplay(mHolder);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mCamera.startPreview();
            } else {
                reverseCamera.setVisibility(View.GONE);
            }
        }

    });

    public static void setCameraDisplayOrientation(Activity activity,
                                               int cameraId, android.hardware.Camera camera) {
    android.hardware.Camera.CameraInfo info =
            new android.hardware.Camera.CameraInfo();
    android.hardware.Camera.getCameraInfo(cameraId, info);
    int rotation = activity.getWindowManager().getDefaultDisplay()
            .getRotation();
    int degrees = 0;
    switch (rotation) {
        case Surface.ROTATION_0:
            degrees = 0;
            break;
        case Surface.ROTATION_90:
            degrees = 90;
            break;
        case Surface.ROTATION_180:
            degrees = 180;
            break;
        case Surface.ROTATION_270:
            degrees = 270;
            break;
    }

    int result;
    if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
        result = (info.orientation + degrees) % 360;
        result = (360 - result) % 360;  // compensate the mirror
    } else {  // back-facing
        result = (info.orientation - degrees + 360) % 360;
    }
    camera.setDisplayOrientation(result);
}

答案 1 :(得分:0)

您可以附加AndroidManifest.xml文件吗?

也许你忘了添加使用相机的许可。

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

更多信息,您可以camera class