Camera camera = Camera.open(); camera.setPreviewCallback(new Camera.PreviewCallback() { @Override public void onPreviewFrame(byte[] data, Camera camera) { // process preview frame here } });
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback { private Camera mCamera; public CameraPreview(Context context) { super(context); SurfaceHolder holder = getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } @Override public void surfaceCreated(SurfaceHolder holder) { mCamera = Camera.open(); mCamera.setPreviewCallback(this); mCamera.setDisplayOrientation(90); try { mCamera.setPreviewDisplay(holder); } catch (IOException e) { e.printStackTrace(); } mCamera.startPreview(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // handle surface changes here } @Override public void surfaceDestroyed(SurfaceHolder holder) { mCamera.setPreviewCallback(null); mCamera.stopPreview(); mCamera.release(); } @Override public void onPreviewFrame(byte[] data, Camera camera) { // process preview frame here } }In this example, we are creating a custom SurfaceView to display the camera preview and setting a preview callback to process each frame that is passed to the callback. We are also handling surface changes and releasing the camera when the SurfaceView is destroyed. Package library: android.view, android.hardware