Android应用中拍照和录制视频都需要Surface,所以需要创建在Activiy中存在SurfaceView或者VideoView,可以在xml中配置,在代码中加载。同时主Activity中需要implementsSurfaceHolder.Callback,实现其中的surfaceCreate,surfaceChanged,surfaceDestoryed三个方法。具体流程如下

First:

SurfaceViewmSurfaceView=(SurfaceView)findViewById(R.id.surfaceview);

SurfaceHoldermHolder=mSurfaceView.getHolder();

mHolder.addCallback(this);

当调用addCallback的时候,就会触发SurfaceHolder.Callback回调,执行surfaceCreate方法,可以在surfaceCreate中做一些初始化。

Second:

打开摄像头,进行初始化。如:

CameramCamera=Camera.open();

mCamera.setPreviewDisplay(mHolder);

当surfaceview被覆盖或者应用结束退出时,surface会destory,执行surfaceDestoryed回调,可以在该回调中释放Camera,如:

mCamera.stopPrevew();

mCamera.release();

mCamera=null;

Thrid:

进行拍照时,调用takePicture接口,传入callback参数,并在最后一个callback中获取byte[]data,并将数据以jpg文件格式保存,如下所示:

mCamera.takePicture(newShutterCallback(){},newPictureCallback(){},newPictureCallback(){},newPictureCallback(){publicvoidonPictureTaken(byte[]data,Cameracamera){save(data)}});

在save方法中通过流输出到指定路径:

FilemediaStoragePath=newFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"PicFiles");

StringfileName=mediaStoragePath.getPath()+File.sperator+"PIC_"+System.currentTimeMills()+".jpg";

FilepictureFile=newFile(fileName);

FileOutputStreamfos=newFileOutputStream(picture);

fos.write(data);

fos.close();