Android相机无法从后台服务拍照

时间:2014-01-30 17:47:40

标签: android service background camera photo

我已经实现了一个服务来从后台线程拍照,但照片永远不会被我的任何设备拍摄......这是代码(下面的日志输出):

public class PhotoCaptureService extends Service {
    private static final String TAG = "PhotoCaptureService";

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d(TAG, "Starting the PhotoCaptureService");
        takePhoto();
    }

    private void takePhoto() {

        Log.d(TAG, "Preparing to take photo");
        Camera camera = null;

        try {

            camera = Camera.open();

        } catch (RuntimeException e) {

            Log.e(TAG, "Camera not available", e);
            return;
        }

        if (null == camera) {

            Log.e(TAG, "Could not get camera instance");
            return;
        }

        Log.d(TAG, "Got the camera, creating the dummy surface texture");
        SurfaceTexture dummySurfaceTexture = new SurfaceTexture(0);

        try {

            camera.setPreviewTexture(dummySurfaceTexture);

        } catch (Exception e) {

            Log.e(TAG, "Could not set the surface preview texture", e);
        }

        Log.d(TAG, "Preview texture set, starting preview");

        camera.startPreview();

        Log.d(TAG, "Preview started");

        camera.takePicture(null, null, new Camera.PictureCallback() {

            @Override
            public void onPictureTaken(byte[] data, Camera camera) {

                Log.d(TAG, "Photo taken, stopping preview");

                camera.stopPreview();

                Log.d(TAG, "Preview stopped, releasing camera");

                camera.release();

                Log.d(TAG, "Camera released");
            }
        });
    }

记录输出:

D/PhotoCaptureService﹕ Starting the PhotoCaptureService
D/PhotoCaptureService﹕ Preparing to take photo
D/PhotoCaptureService﹕ Got the camera, creating the dummy surface texture
D/PhotoCaptureService﹕ Preview texture set, starting preview
D/PhotoCaptureService﹕ Preview started

此时没有其他事情发生,onPictureTaken方法永远不会被调用,并且没有抛出错误或异常。有谁知道为什么会这样?我看过StackOverflow上的每一个相机教程,似乎没什么用。

1 个答案:

答案 0 :(得分:1)

根据我的经验以及我所阅读的内容,虚拟SurfaceTexture策略并不适用于所有手机。请尝试添加1x1像素SurfaceView并在SurfaceView.getHolder()的{​​{1}}回调中开始预览(通过onSurfaceCreated添加)。

有关详细信息,请参阅Taking picture from camera without preview

相关问题