Search code examples
androidcamerasurfaceviewpreview

Android Camera Preview not working in virtual phone


I made a surfaceview that should display the camera preview. However, When I open it with my virtual android phone, I get a checkered black and white background and a large moving green box instead of the actual camera image.

Here is the code for the surfaceview:

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{

private Camera camera;
private SurfaceHolder surfaceholder;

public CameraPreview(Context context) {
    super(context);
    surfaceholder= getHolder();
    surfaceholder.addCallback(this);
    surfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)   {
    Camera.Parameters parameters = camera.getParameters();
    parameters.setPreviewSize(width, height);
    parameters.setPictureFormat(PixelFormat.JPEG);
    camera.setParameters(parameters);
    camera.startPreview();      
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
    camera = Camera.open();
    try {
        camera.setPreviewDisplay(surfaceholder);
    } catch (IOException e) {}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    stopCam();
}
public void stopCam(){
    if (camera!=null){
        camera.stopPreview();
        camera.release();
    }
}
 }

Solution

  • I'm going to assume "virtual android phone" means the emulator. There is nothing wrong with your code, for the most part cameras are not supported in the emulator (with a few special exceptions), and when the emulator doesn't have a camera to load, it displays that animation instead to emulate a camera preview.

    AFAIK, the only way to get actual primary camera support in the emulator is to use the 4.0.x emulator images on Mac OS X. In this case it can detect and use the built-in iSight camera. Otherwise, you will need to write special code to support webcam connections to the emulator like this article explains: http://www.tomgibara.com/android/camera-source

    HTH