切换后/前置摄像头

时间:2013-12-24 19:03:04

标签: android camera android-camera

我的CameraPreview课程:

public class CameraPreview extends ViewGroup implements SurfaceHolder.Callback {
SurfaceView mSurfaceView;
SurfaceHolder mHolder;
Size mPreviewSize;
List<Size> mSupportedPreviewSizes;
Camera mCamera;

CameraPreview(Context context, SurfaceView sv) {
    super(context);
    mSurfaceView = sv;       
    mHolder = mSurfaceView.getHolder();
    mHolder.addCallback(this);      
}

public void setCamera(Camera camera) {
    mCamera = camera;
    if (mCamera != null) {
        mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
        requestLayout();

        // get Camera parameters
        Camera.Parameters params = mCamera.getParameters();

        List<String> focusModes = params.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            // set the focus mode
            params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            // set Camera parameters
            mCamera.setParameters(params);
        }
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // We purposely disregard child measurements because act as a
    // wrapper to a SurfaceView that centers the camera preview instead
    // of stretching it.

    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
    setMeasuredDimension(width, height);

    if (mSupportedPreviewSizes != null) {
       mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
    }
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if (changed && getChildCount() > 0) {
        final View child = getChildAt(0);

        final int width = r - l;
        final int height = b - t;

        int previewWidth = width;
        int previewHeight = height;
        if (mPreviewSize != null) {
            previewWidth = mPreviewSize.width;
            previewHeight = mPreviewSize.height;
        }

        // Center the child SurfaceView within the parent.
        if (width * previewHeight > height * previewWidth) {
            final int scaledChildWidth = previewWidth * height / previewHeight;
            child.layout((width - scaledChildWidth) / 2, 0,
                    (width + scaledChildWidth) / 2, height);
        } else {
            final int scaledChildHeight = previewHeight * width / previewWidth;
            child.layout(0, (height - scaledChildHeight) / 2,
                    width, (height + scaledChildHeight) / 2);
        }
    }
}

public void surfaceCreated(SurfaceHolder holder) {
    // The Surface has been created, acquire the camera and tell it where
    // to draw.
    try {
        if (mCamera != null) {
            mCamera.setPreviewDisplay(holder);
        }
    } catch (IOException exception) {

    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
    // Surface will be destroyed when we return, so stop the preview.
    if (mCamera != null) {
        mCamera.stopPreview();
    }
}


private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio=(double)h / w;

    if (sizes == null) return null;

    Camera.Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    for (Camera.Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    if (optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Camera.Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }
    return optimalSize;
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    if(mCamera != null) {
        mCamera.setDisplayOrientation(90);          
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
        requestLayout();
        mCamera.setParameters(parameters);
        mCamera.startPreview();             
    }
}
}

我的普通班:

public class PhotoMode extends Activity {
CameraPreview preview;
Camera camera;
String fileName;
Activity act;
Context ctx;

private int currentCameraId = 2;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ctx = this;
    act = this;
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.photomode);

    preview = new CameraPreview(this, (SurfaceView)findViewById(R.id.surfaceView));
    ((FrameLayout) findViewById(R.id.preview)).addView(preview);
    preview.setKeepScreenOn(true);

    Button button_swith = (Button) findViewById(R.id.button_swith);
    button_swith.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            toggleCamera();                 
        }
    });         
}

private void toggleCamera() {
        if (camera != null) {
            camera.stopPreview(); 
        }
        camera.release();
        if (currentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK){
            currentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;            
        }
        else if (currentCameraId == Camera.CameraInfo.CAMERA_FACING_FRONT){
            currentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
        }

        camera = Camera.open(currentCameraId);
        camera = Camera.open();
        camera.startPreview();
        preview.setCamera(camera);          
 }  

@Override
protected void onResume() {
    super.onResume();       
    camera = Camera.open();
    camera.startPreview();
    preview.setCamera(camera);
}

@Override
protected void onPause() {
    if(camera != null) {
        camera.stopPreview();
        preview.setCamera(null);
        camera.release();
        camera = null;
    }
    super.onPause();
}   
}

方法toggleCamera()调用错误:

12-24 21:11:14.409: E/AndroidRuntime(26675): FATAL EXCEPTION: main
12-24 21:11:14.409: E/AndroidRuntime(26675): java.lang.RuntimeException: Fail to connect to camera service
12-24 21:11:14.409: E/AndroidRuntime(26675):    at android.hardware.Camera.native_setup(Native Method)
12-24 21:11:14.409: E/AndroidRuntime(26675):    at android.hardware.Camera.<init>(Camera.java)
12-24 21:11:14.409: E/AndroidRuntime(26675):    at android.hardware.Camera.open(Camera.java)
12-24 21:11:14.409: E/AndroidRuntime(26675):    at com.example.photomode.PhotoMode.toggleCamera(PhotoMode.java:58)
12-24 21:11:14.409: E/AndroidRuntime(26675):    at com.example.photomode.PhotoMode.access$0(PhotoMode.java:46)
12-24 21:11:14.409: E/AndroidRuntime(26675):    at com.example.photomode.PhotoMode$1.onClick(PhotoMode.java:41)
12-24 21:11:14.409: E/AndroidRuntime(26675):    at android.view.View.performClick(View.java)
12-24 21:11:14.409: E/AndroidRuntime(26675):    at android.view.View$PerformClick.run(View.java)

在清单中是:

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

我哪里出错了?感谢

3 个答案:

答案 0 :(得分:0)

您必须将相机发布到toggleCamera()方法中。尝试不使用camera.release()

答案 1 :(得分:0)

camera = Camera.open(currentCameraId);
camera = Camera.open();

为什么open()被调用两次?尝试删除第二行?

答案 2 :(得分:0)

添加更多:

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