get Camera Instance - Android android.hardware

Android examples for android.hardware:Camera

Description

get Camera Instance

Demo Code

import android.hardware.Camera;

public class Main {

  public static int mOrientationOfCameraImage = 0;

  /**/*  w  w  w. j a v  a2 s .c o 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 = getNumberOfCameras();
    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