在视觉处理或者图像处理中,我们常常会用到相机后台预览或者拍摄视频,预览得到的图像集或拍摄得到的视频流,就可以用于实时的算法处理。其实这里的的后台预览并不一定要是通过后台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.
Android Camera2后台预览与视频拍摄的黑屏异常解决方案

本文介绍了在Android应用中使用Camera2进行后台预览和拍摄视频时遇到黑屏后应用异常停止的问题。通过分析Google的Camera2Basic示例代码并尝试使用WakeLock和保持屏幕常亮等方式,最终发现启动前台服务可以有效解决这一问题,确保相机在黑屏状态下仍能持续预览和拍摄。
最低0.47元/天 解锁文章
3938





