上篇文章介绍了,Camera初始化的过程,完成初始化之后就可以使用Camera提供的以下功能了
1.预览preview
2.视频录制
3.拍照和参数设置
打开Camera第一键事情就是预览取景preview的动作,我们先从Camera app分析起 。所有拥有拍照功能的应用,它在预览时候都要实现SurfaceHolder.Callback接口,并实现其surfaceCreated、surfaceChanged、surfaceDestroyed三个函数,同时声明一个用于预览的窗口SurfaceView ,以下是系统自带ap的源代码
SurfaceView preview = (SurfaceView) findViewById(R.id.camera_preview);
SurfaceHolder holder = preview.getHolder();
holder.addCallback(this);
还要设置camera预览的surface缓存区 ,系统自带app实在surfaceChange()方法里面设置Camera的预览区,以供底层获取的preview数据不断投递到这个surface缓存区内。
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
mSurfaceHolder = holder;
// The mCameraDevice will be null if it fails to connect to the camera
// hardware. In this case we will show a dialog and then finish the
// activity, so it's OK to ignore it.
if (mCameraDevice == null) return;
// Sometimes surfaceChanged is called after onPause or before onResume.
// Ignore it.
if (mPausing || isFinishing()) return;
// Set preview display if the surface is being created. Preview was
// already started. Also restart the preview if display rotation has
// changed. Sometimes this happens when the device is held in portrait
// and camera app is opened. Rotation animation takes some time and
// display rotation in onCreate may not be what we want.
if (mCameraState == PREVIEW_STOPPED) {
startPreview();
startFaceDetection();
} else {
if (Util.getDisplayRotation(this) != mDisplayRotation) {
setDisplayOrientation();
}
if (holder.isCreating()) {
// Set preview display if the surface is being created and preview
// was already started. That means preview display was set to null
// and we need to set it now.
setPreviewDisplay(holder);
}
}
设置好以上参数后,就可以调用startPreview()进行取景预览
startPreview()也是一层层往下调用,最后到Camera的服务端CameraService,我们看下它的过程
Camera.java(应用)-------------> Camera.java(框架)-------------->android_hardware_camera.cpp(JNI)-------------------->Camera.cpp(客户端)------------------