A safe way to get an instance of the Camera object by facing - Android Camera

Android examples for Camera:Camera Facing

Description

A safe way to get an instance of the Camera object by facing

Demo Code


import android.hardware.Camera;

public class Main {
  public static int mOrientationOfCameraImage = 0;

  /**//from   ww w.  j ava  2 s .  co m
   * A safe way to get an instance of the Camera object.
   *
   * @param facing
   *          {Camera.CameraInfo.CAMERA_FACING_FRONT,
   *          Camera.CameraInfo.CAMERA_FACING_BACK}
   * @return a camera instance if the device has a camera of specified facing and
   *         the camera is not in use, or will return null
   */
  public static Camera getCameraInstance(int facing) {

    if (facing != Camera.CameraInfo.CAMERA_FACING_BACK && facing != Camera.CameraInfo.CAMERA_FACING_FRONT) {
      return null;
    }

    Camera camera = null;
    int number = 3;
    for (int i = 0; i < number; i++) {
      Camera.CameraInfo ci = new Camera.CameraInfo();
      Camera.getCameraInfo(i, ci);
      if (ci.facing == facing) {
        try {
          camera = Camera.open(i);
          mOrientationOfCameraImage = ci.orientation;
          // Log.d("Orientation:", "" + ci.orientation);
        } catch (Exception e) {
          e.printStackTrace();
        }
        break;
      }
    }

    return camera;
  }

  /**
   * Get the number of cameras that the android device owned.
   *
   * @return number of cameras.
   */
  public static int getNumberOfCameras() {
    return Camera.getNumberOfCameras();
  }
}

Related Tutorials