[android]打开前面 camera 在 surface view

标签: Java Android
发布时间: 2016/9/26 4:14:48
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我得到了异常 java.lang.RuntimeException: Fail to get camera infoCamera.getCameraInfo(cameraId,info);

我的代码是︰

public void surfaceCreated(SurfaceHolder holder) {
    int cameraId = -1;
    for(int i=0;i<Camera.getNumberOfCameras();i++){
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId,info);
        if(info.facing== Camera.CameraInfo.CAMERA_FACING_FRONT){
            cameraId = i;
            break;
        }
    }
    camera = Camera.open(cameraId);
}

manifest 也有︰

<uses-permission android:name="android.permission.CAMERA" />

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

什么东西是缺掉的和如何解决这个问题吗? 任何帮助是欢迎的。

解决方法 1:

我改变了方法;以前我在实现 SurfaceHolder.Callback 但现在创建了它的对象。

我移动代码从 SurfaceCreatedonResume()

public void onResume() {
    super.onResume();
    for(int i=0;i<Camera.getNumberOfCameras();i++){
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(i,info);
        if(info.facing== Camera.CameraInfo.CAMERA_FACING_FRONT){
            cameraId = i;
            break;
        }
    }
    camera=Camera.open(cameraId);
    camera.startPreview();
}

的回调对象就像︰

SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
    public void surfaceCreated(SurfaceHolder holder) {
        // no-op -- wait until surfaceChanged()

    }
    public void surfaceChanged(SurfaceHolder holder,
                               int format, int width,
                               int height) {
        Camera.Parameters parameters=camera.getParameters();
        Camera.Size size=getBestPreviewSize(width, height,
                    parameters);
        Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();

        if (size!=null) {
            parameters.setPreviewSize(size.width, size.height);
            camera.setParameters(parameters);
            camera.setDisplayOrientation(90);
            cameraConfigured=true;
        }
        camera.startPreview();
    }
    public void surfaceDestroyed(SurfaceHolder holder) {
        // no-op
    }
};

这解决了我的问题。

赞助商