Android應用中拍照和錄製視頻都需要Surface,所以需要創建在Activiy中存在SurfaceView或者VideoView,可以在xml中配置,在代碼中加載。同時主Activity中需要implements SurfaceHolder.Callback,實現其中的surfaceCreate, surfaceChanged, surfaceDestoryed三個方法。具體流程如下
First:
SurfaceView mSurfaceView = (SurfaceView)findViewById(R.id.surfaceview);
SurfaceHolder mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
當調用addCallback的時候,就會觸發SurfaceHolder.Callback回調,執行surfaceCreate方法,可以在surfaceCreate中做一些初始化。
Second:
打開攝像頭,進行初始化。如:
Camera mCamera = 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(new ShutterCallback(){}, new PictureCallback(){},new PictureCallback(){}, new PictureCallback(){public void onPictureTaken(byte[] data, Camera camera) {save(data)} });
在save方法中通過流輸出到指定路徑:
File mediaStoragePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "PicFiles");
String fileName = mediaStoragePath.getPath() + File.sperator + "PIC_" + System.currentTimeMills() + ".jpg";
File pictureFile = new File(fileName);
FileOutputStream fos = new FileOutputStream(picture);
fos.write(data);
fos.close();