且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以在没有预览的情况下在服务中使用Android相机吗?

更新时间:2022-01-11 21:19:10

您可以参考

You can refer this Question, which discuss how to do video record in the service. The steps to capture image is same as it.

要满足您的要求,您可能需要:

To achieve your requirement, you may need:

  1. 在您的服务中获取相机实例.检查此官方指南.
  2. 设置相机参数.使用Camera.getParameters()Camera.setParameters()Camera.Parameters.setPictureSize(int with, int height)Camera.Parameters.setPictureFormat(int format)之类的API来做到这一点.
  3. 准备用于存储图像的文件.您需要实现Camera.PictureCallback来实现.
  4. 拍照前请致电Camera.startPreview().如果您未在拍照前调用此功能,则会出现异常. (注意:您无需先执行Camera.setPreviewdisplay(SurfaceHolder display).)
  5. 在您的服务中致电camera.takePicture().然后,您可以将捕获的图像存储在指定的文件中.
  1. Get camera instance in your service. Check this Official Guideline.
  2. Setup your camera parameters. Use the APIs like Camera.getParameters(), Camera.setParameters(), Camera.Parameters.setPictureSize(int with, int height) and Camera.Parameters.setPictureFormat(int format) to do so.
  3. Prepare a file used to store the image. You need to implement Camera.PictureCallback to do so.
  4. Call Camera.startPreview() before you takeing picutre. If you don't call this function before taking picture, you will get exception. (Note: You don't need to do Camera.setPreviewdisplay(SurfaceHolder display) first.)
  5. Call camera.takePicture() in your service. Then you can get the captured image stored on the file you specified.

工作后,请不要忘记维护资源消耗生命周期,以正确获取/释放摄像机.

After it work, don forget to maintain the resource durning lifecycle to acquire/release camera correctly.

这是我在Github上的示例代码,在评论中也有提及.

Here is my sample code on Github, it is also mentioned in the comment.