android:相机没有拍照

时间:2015-05-16 11:54:25

标签: android camera

这个想法很简单:我的应用程序应该创建一个相机对象,显示预览并拍照(不按任何按钮),然后关闭相机。不幸的是它甚至没有拍任何照片。 (意思是:永远不会在拍摄照片后执行我的回调代码。)

我正在为android camera api使用一个小包装类。我的活动代码如下所示:

camera = new SurveillanceCamera(this, layoutForPreview);
camera.start();
camera.takePicture();

包装类:

public SurveillanceCamera(Context context, LinearLayout previewLayout) {
    cameraInstance = Camera.open(findBackFacingCamera());
    pictureCallback = getPictureCallback();
    cameraPreview = new CameraPreview(context, cameraInstance);
    this.previewLayout = previewLayout;
    this.previewLayout.addView(cameraPreview);
    cameraInstance.startPreview();
  }

  public void takePicture() {
    //this code is reached
    cameraInstance.takePicture(null, null, pictureCallback);
  }

  public void start() {
    if (cameraInstance == null) {
      cameraInstance = Camera.open(findBackFacingCamera());
      pictureCallback = getPictureCallback();
      cameraPreview.setCamera(cameraInstance);
      cameraInstance.startPreview();
    }
  }

  private PictureCallback getPictureCallback() {
    PictureCallback picture = new PictureCallback() {
      @Override
      public void onPictureTaken(byte[] data, Camera camera) {
        Log.e(TAG, "Jey picture was taken...");
        // refresh camera to continue preview
        cameraPreview.refreshCamera(cameraInstance);
      }
    };
    return picture;
  }

  private int findBackFacingCamera() {
    int cameraId = -1;
    // Search for the back facing camera
    // get the number of cameras
    int numberOfCameras = Camera.getNumberOfCameras();
    // for every camera check
    for (int i = 0; i < numberOfCameras; i++) {
      CameraInfo info = new CameraInfo();
      Camera.getCameraInfo(i, info);
      if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
        cameraId = i;
        break;
      }
    }
    return cameraId;
  }

代码中没有抛出异常,但onPictureTaken中的Log.e()未显示。似乎显示了相机预览但没有任何反应。是否有可能在执行camera.takePicture()时预览未完全加载?有什么建议吗?

1 个答案:

答案 0 :(得分:0)

你的怀疑很可能是合理的。我不知道何时调用setPreviewDisplay()。但是,此调用应该完成takePicture()才能成功。

简单地调用

是不可能的
camera = new SurveillanceCamera(this, layoutForPreview);
camera.start();
camera.takePicture();

因为要完成setPreviewDisplay()调用,您需要一个完全初始化的Holder实例,但只需在构造函数中添加表面视图。

最好注册SurfaceHolder.Callback并从surfaceChanged()回调中拨打takePicture()