在视觉处理或者图像处理中,我们常常会用到相机后台预览或者拍摄视频,预览得到的图像集或拍摄得到的视频流,就可以用于实时的算法处理。其实这里的的后台预览并不一定要是通过后台service来开启相机预览,根本的要求是,应用退出后或者手机黑屏后相机依然能够进行预览或者拍摄视频。
关于Camera2如何实现预览的代码,Google提供的sample就很经典,大多都是从它这修改过来的:
https://github.com/googlearchive/android-Camera2Basic
这里的代码是通常的前台预览的,我们稍稍改动一下,注释掉onPause和onResume中的相机启动关闭代码,改为单独接口,然后通过activity控制在适当的时候调用就可以实现后台预览:
@Override
public void onResume() {
super.onResume();
/*startBackgroundThread();
// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
// a camera and start preview from here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView.getHeight());
} else {
mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
}*/
}
@Override
public void onPause() {
/*closeCamera();
stopBackgroundThread();*/
super.onPause();
}
public synchronized void start() {
if (mCameraDevice != null) {
return;
}
startBackgroundThread();
// When the screen is turned off and turned back on, the SurfaceTexture is already
// available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
// a camera and start preview from here (otherwise, we wait until the surface is ready in
// the SurfaceTextureListener).
if (mTextureView.isAvailable()) {
openCamera(mTextureView.getWidth(), mTextureView