博客地址:zeyang’s blog
最近做的项目里要求在通知栏里有一个按钮,点击按钮立刻拍照,并且显示在图库里.
在经过了几天的研究之后终于实现了,中途走了不少的弯路.先是没有传入预览界面,只调用startPreview();方法就实现了拍照,并且在两部手机上都可以正常使用,但在小米手机上不行…..很忧桑得以为是小米手机的权限问题…后来查看官方文档和stackoverflow发现之前测试成功纯属运气…
官方文档:
To take pictures with this class, use the following steps:
1.Obtain an instance of Camera from open(int).
2.Get existing (default) settings with getParameters().
3.If necessary, modify the returned Camera.Parameters object and call setParameters(Camera.Parameters).
4.If desired, call setDisplayOrientation(int).
5.Important: Pass a fully initialized SurfaceHolder to setPreviewDisplay(SurfaceHolder). Without a surface, the camera will be unable to start the preview.
6.Important: Call startPreview() to start updating the preview surface. Preview must be started before you can take a picture.
7.When you want, call takePicture(Camera.ShutterCallback, Camera.PictureCallback, Camera.PictureCallback,
Camera.PictureCallback) to capture a photo. Wait for the callbacks to
provide the actual image data.
8.After taking a picture, preview display will have stopped. To take more photos, call startPreview() again first.
9.Call stopPreview() to stop updating the preview surface.
10.Important: Call release() to release the camera for use by other applications. Applications should release the camera immediately
in onPause() (and re-open() it in onResume()).
发现在拍照前一定要预览,否则无法拍照(在有些手机上仅仅调用startpreview()而没有传入界面就可以拍照).
所以想到用悬浮框或者activity显示界面,因为悬浮窗常常有系统限制,所以尝试用activity.
基本思路:在通知栏里写一个按钮,接受到响应之后用intent开启一个透明的activity来拍照,拍照完成后关闭activity.
一下是部分代码:
用于拍照的activity(不可见)
需要的权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
开启这个抓拍的activity需要在intent上添加
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
抓拍的activity:
public class AndroidCameraActivity extends Activity {
private CameraSurfacePreview mCameraSurPreview = null;
private static String imgPath = null;
private static String imgName = null;
public final static String PATH_KEY = "path";
public final static String NAME_KEY = "name";
public final static String RESULT_KEY = "result";
public final</