private Camera mCamera; private CameraPreview mPreview;
// Create an instance of Camera mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity. mPreview = new CameraPreview(this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview);
// get an instance of the Camera object public static Camera getCameraInstance(){ Camera c = null; try { c = Camera.open(); // attempt to get a Camera instance } catch (Exception e){ // Camera is not available (in use or does not exist) } return c; // returns null if camera is unavailable }
private SurfaceHolder mHolder;
private class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { private Camera mCamera; private PreviewCallback mPreviewCallback = new PreviewCallback() { public void onPreviewFrame(byte[] data, Camera camera) { // Process the preview image } };
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
}
public void surfaceCreated(SurfaceHolder holder) {
// Start the preview
try {
mCamera.setPreviewDisplay(holder);
mCamera.setPreviewCallback(mPreviewCallback);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Release the camera
mCamera.stopPreview();
mHolder.removeCallback(this);
mCamera.release();
mCamera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Adjust the preview layout
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes