我已经实现了一个从后台线程拍摄照片的服务,但是照片永远不会在我的任何设备上拍摄…下面是代码(记录输出):

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的相机教程,但似乎什么都没用。

最佳答案

根据我的经验和我读过的资料,dummySurfaceTexture策略并不适用于所有手机。尝试添加1x1像素并在SurfaceViewSurfaceView.getHolder()回调中启动预览(通过onSurfaceCreated添加)。
有关更多信息,请参见Taking picture from camera without preview

07-21 21:50