开发者

How to properly lock/unlock camera when drawing on SurfaceView?

I created an开发者_如何学Go Activity with Augmented Reality functionality. Part of that is to have phone camera display in the background (which is SurfaceView in Activity layout).

in activity onCreate() method I do:

surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);

My callbacks are:

@Override
public void surfaceCreated(SurfaceHolder holder) {

    try {
        camera = Camera.open();
        camera.setDisplayOrientation(90);
        camera.setPreviewDisplay(holder);
    } catch (Exception e) {
        // e.printStackTrace();
    }
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    camera.startPreview();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    camera.stopPreview();
    camera.release();
}

Right now when I close my application (while leaving it in the background) Camera app is not working because Camera is still locked inside my app.

How should I implement activity onResume() onPause() methods in order to lock/unlock camera?

Also leaving camera locked in the app takes up about 5% of CPU on Galaxy S and after I come back to my app - it crashes in surfaceChanged() when trying to camera.startPreview();

Help!


Just add something like this to surfaceCreated callback:

    if (camera != null) {
        camera.release();
    }
    camera = Camera.open();
    camera.setDisplayOrientation(90);
    try {
        camera.setPreviewDisplay(holder);
    } catch (Exception e) {
    }

And then inside onPause() add release and call to callback:

    camera.release();
    surfaceCreated(surfaceHolder);

Now it works like a charm! Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜