Java Code Examples for android.hardware.camera2.CameraManager#getCameraIdList()

The following examples show how to use android.hardware.camera2.CameraManager#getCameraIdList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Helper.java    From VIA-AI with MIT License 8 votes vote down vote up
public void forceScanAllCameras(Activity activity) {
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        String[] idList = manager.getCameraIdList();

        int maxCameraCnt = idList.length;

        for (int index = 0; index < maxCameraCnt; index++) {
            String cameraId = manager.getCameraIdList()[index];
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

}
 
Example 2
Source File: CameraXUtil.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(21)
public static int getLowestSupportedHardwareLevel(@NonNull Context context) {
  @SuppressLint("RestrictedApi") CameraManager cameraManager = CameraManagerCompat.from(context).unwrap();

  try {
    int supported = maxHardwareLevel();

    for (String cameraId : cameraManager.getCameraIdList()) {
      CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
      Integer               hwLevel         = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);

      if (hwLevel == null || hwLevel == CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
        return CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY;
      }

      supported = smallerHardwareLevel(supported, hwLevel);
    }

    return supported;
  } catch (CameraAccessException e) {
    Log.w(TAG, "Failed to enumerate cameras", e);

    return CameraMetadata.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY;
  }
}
 
Example 3
Source File: Camera2DeviceTester.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
public CameraDevice captureCameraDevice() throws Exception {
    CameraManager manager =
            (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
    String id = manager.getCameraIdList()[0];
    synchronized (this) {
        manager.openCamera(id, this, sHandler);
        wait();
    }
    return mCamera;
}
 
Example 4
Source File: MediaSnippetsActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initCamera() {
  cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

  String[] cameraIds = new String[0];

  try {
    cameraIds = cameraManager.getCameraIdList();
    if (cameraIds.length == 0) return;

    cameraId = cameraIds[0];
  } catch (CameraAccessException e) {
    Log.e(TAG, "Camera Error.", e);
    return;
  }
}
 
Example 5
Source File: VideoCameraActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void initCamera() {
  try {
    CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String[] cameraIds = cameraManager.getCameraIdList();
    if (cameraIds.length == 0) return;

    String cameraId = cameraIds[0];

    if (ActivityCompat.checkSelfPermission(this,
      Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(this,
        new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSIONS_REQUEST);
    }

    cameraManager.openCamera(cameraId, cameraDeviceCallback, null);
  } catch (CameraAccessException e) {
    Log.d(TAG, "No access to the camera.", e);
  }
}
 
Example 6
Source File: Camera2Helper.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * 指定されたカメラIDの向きを取得します.
 *
 * @param cameraManager カメラマネージャ
 * @param id カメラID
 * @return 向き
 * @throws CameraAccessException カメラの操作に失敗した場合に発生
 */
public static int getFacing(final CameraManager cameraManager, final String id) throws CameraAccessException {
    for (String cameraId : cameraManager.getCameraIdList()) {
        if (cameraId.equals(id)) {
            CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null) {
                return facing;
            }
        }
    }
    return -1;
}
 
Example 7
Source File: CameraUtils.java    From SimpleSmsRemote with MIT License 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static Iterable<MyCameraInfo> GetAllCamerasIterable2(Context context) throws Exception {
    final CameraManager cameraManager =
            (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    final String[] cameraIdList = cameraManager.getCameraIdList();

    return new Iterable<MyCameraInfo>() {
        @Override
        public Iterator<MyCameraInfo> iterator() {
            return new Iterator<MyCameraInfo>() {
                private int pos = 0;

                @Override
                public boolean hasNext() {
                    return pos < cameraIdList.length;
                }

                @Override
                public MyCameraInfo next() {
                    String cameraId = cameraIdList[pos++];
                    CameraCharacteristics characteristics;
                    try {
                        characteristics = cameraManager.getCameraCharacteristics(cameraId);
                        return MyCameraInfo.CreateFromCameraCharacteristics(cameraId,
                                characteristics);
                    } catch (CameraAccessException e) {
                        return null;
                    }
                }
            };
        }
    };
}
 
Example 8
Source File: BaseCameraActivity.java    From fritz-examples with MIT License 5 votes vote down vote up
private String chooseCamera() {
    final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        for (final String cameraId : manager.getCameraIdList()) {
            final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

            // We don't use a front facing camera in this sample.
            final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing != cameraFacingDirection) {
                continue;
            }

            final StreamConfigurationMap map =
                    characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

            if (map == null) {
                continue;
            }

            // Fallback to camera1 API for internal cameras that don't have full support.
            // This should help with legacy situations where using the camera2 API causes
            // distorted or otherwise broken previews.
            useCamera2API = (facing == CameraCharacteristics.LENS_FACING_EXTERNAL)
                    || isHardwareLevelSupported(characteristics,
                    CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL);
            Log.i(TAG, "Camera API lv2?: " + useCamera2API);
            return cameraId;
        }
    } catch (CameraAccessException e) {
        Log.e(TAG, "Not allowed to access camera: " + e);
    }

    return null;
}
 
Example 9
Source File: Camera2Helper.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * 指定された facing に対応するカメラIDを取得します.
 * <p>
 * facing に対応したカメラが発見できない場合には null を返却します。
 * </p>
 * @param cameraManager カメラマネージャ
 * @param facing カメラの向き
 * @return カメラID
 * @throws CameraAccessException カメラの操作に失敗した場合に発生
 */
public static String getCameraId(final CameraManager cameraManager, final int facing) throws CameraAccessException {
    for (String cameraId : cameraManager.getCameraIdList()) {
        CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
        Integer supportFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
        if (supportFacing != null && supportFacing == facing) {
            return cameraId;
        }
    }
    return null;
}
 
Example 10
Source File: CameraHandler.java    From androidthings-imageclassifier with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
@SuppressLint("MissingPermission")
public void initializeCamera(Context context, int previewWidth, int previewHeight,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    if (initialized) {
        throw new IllegalStateException(
                "CameraHandler is already initialized or is initializing");
    }
    initialized = true;

    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
    String[] camIds = null;
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.w(TAG, "Cannot get the list of available cameras", e);
    }
    if (camIds == null || camIds.length < 1) {
        Log.d(TAG, "No cameras found");
        return;
    }
    Log.d(TAG, "Using camera id " + camIds[0]);

    // Initialize the image processor
    mImageReader = ImageReader.newInstance(previewWidth, previewHeight, ImageFormat.JPEG,
            MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(camIds[0], mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
 
Example 11
Source File: CameraOperator.java    From android-robocar with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void init(Context context) throws CameraAccessException {
  inSession = false;

  if (!ImageSaver.isExternalStorageWritable()) {
    Timber.e("Cannot save file, external storage is not writable.");
    return;
  }

  File root = ImageSaver.getRoot(ROBOCAR_FOLDER);
  if (root == null) {
    Timber.e("Failed to create destination folder.");
    return;
  }

  CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
  String[] cameras = manager.getCameraIdList();
  if (cameras.length == 0) {
    Timber.e("No cameras available.");
    return;
  }

  Timber.d("Default camera selected (%s), %d cameras found.",
      cameras[CAMERA_INDEX], cameras.length);

  if (ActivityCompat.checkSelfPermission(
      context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
    Timber.d("Camera permission not granted yet, restart your device.");
    return;
  }

  // Debug and check for autofocus support
  dumpFormatInfo(manager, cameras[CAMERA_INDEX]);

  startBackgroundThread();
  deviceCallback = new DeviceCallback();
  manager.openCamera(cameras[CAMERA_INDEX], deviceCallback, backgroundHandler);
}
 
Example 12
Source File: Camera2Helper.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * 指定されたカメラIDの向きを取得します.
 *
 * @param cameraManager カメラマネージャ
 * @param id カメラID
 * @return 向き
 * @throws CameraAccessException カメラの操作に失敗した場合に発生
 */
static int getFacing(final CameraManager cameraManager, final String id) throws CameraAccessException {
    for (String cameraId : cameraManager.getCameraIdList()) {
        if (cameraId.equals(id)) {
            CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null) {
                return facing;
            }
        }
    }
    return -1;
}
 
Example 13
Source File: DoorbellCamera.java    From androidthings-cameraCar with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the camera device
 */
public void initializeCamera(Context context,
                             Handler backgroundHandler,
                             ImageReader.OnImageAvailableListener imageAvailableListener) {
    // Discover the camera instance
    CameraManager manager = (CameraManager) context.getSystemService(CAMERA_SERVICE);
    String[] camIds = {};
    try {
        camIds = manager.getCameraIdList();
    } catch (CameraAccessException e) {
        Log.d(TAG, "Cam access exception getting IDs", e);
    }
    if (camIds.length < 1) {
        Log.d(TAG, "No cameras found");
        return;
    }
    String id = camIds[0];
    Log.d(TAG, "Using camera id " + id);

    // Initialize the image processor
    mImageReader = ImageReader.newInstance(IMAGE_WIDTH, IMAGE_HEIGHT,
            ImageFormat.JPEG, MAX_IMAGES);
    mImageReader.setOnImageAvailableListener(
            imageAvailableListener, backgroundHandler);

    // Open the camera resource
    try {
        manager.openCamera(id, mStateCallback, backgroundHandler);
    } catch (CameraAccessException cae) {
        Log.d(TAG, "Camera access exception", cae);
    }
}
 
Example 14
Source File: Flashlight.java    From Flashlight-PhoneGap-Plugin with MIT License 5 votes vote down vote up
@TargetApi(21)
private void doToggleTorchSdk23(boolean switchOn) throws IOException, CameraAccessException {
  final CameraManager cameraManager = (CameraManager) cordova.getActivity().getSystemService(Context.CAMERA_SERVICE);
  for (final String id : cameraManager.getCameraIdList()) {
    // Turn on the flash if the camera has one (usually the one at index 0 has one)
    final Boolean hasFlash = cameraManager.getCameraCharacteristics(id).get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
    if (Boolean.TRUE.equals(hasFlash)) {
      setTorchMode(cameraManager, id, switchOn);
      break;
    }
  }
}
 
Example 15
Source File: CameraActivity.java    From dbclf with Apache License 2.0 5 votes vote down vote up
protected String chooseCamera() {
    final CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        for (final String cameraId : manager.getCameraIdList()) {
            final CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);

            // We don't use a front facing camera in this sample.
            final Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                continue;
            }

            final StreamConfigurationMap map =
                    characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

            if (map == null) {
                continue;
            }

            // Fallback to camera1 API for internal cameras that don't have full support.
            // This should help with legacy situations where using the camera2 API causes
            // distorted or otherwise broken previews.
            useCamera2API = (facing == CameraCharacteristics.LENS_FACING_EXTERNAL)
                    || isHardwareLevelSupported(characteristics,
                    CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL);
            return cameraId;
        }
    } catch (CameraAccessException ignored) {
    }

    return null;
}
 
Example 16
Source File: CameraHelper.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static boolean hasCamera2(Context context) {
    if (context == null) return false;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return false;
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] idList = manager.getCameraIdList();
        boolean notNull = true;
        if (idList.length == 0) {
            notNull = false;
        } else {
            for (final String str : idList) {
                if (str == null || str.trim().isEmpty()) {
                    notNull = false;
                    break;
                }
                final CameraCharacteristics characteristics = manager.getCameraCharacteristics(str);

                final int supportLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
                if (supportLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
                    notNull = false;
                    break;
                }
            }
        }
        return notNull;
    } catch (Throwable ignore) {
        return false;
    }
}
 
Example 17
Source File: Camera2ApiManager.java    From rtmp-rtsp-stream-client-java with Apache License 2.0 5 votes vote down vote up
@Nullable
private String getCameraIdForFacing(CameraManager cameraManager, CameraHelper.Facing facing)
    throws CameraAccessException {
  int selectedFacing = getFacing(facing);
  for (String cameraId : cameraManager.getCameraIdList()) {
    Integer cameraFacing =
        cameraManager.getCameraCharacteristics(cameraId).get(CameraCharacteristics.LENS_FACING);
    if (cameraFacing != null && cameraFacing == selectedFacing) {
      return cameraId;
    }
  }
  return null;
}
 
Example 18
Source File: CameraHelper.java    From sandriosCamera with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static boolean hasCamera2(Context context) {
    if (context == null) return false;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return false;
    try {
        CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        String[] idList = manager.getCameraIdList();
        boolean notNull = true;
        if (idList.length == 0) {
            notNull = false;
        } else {
            for (final String str : idList) {
                if (str == null || str.trim().isEmpty()) {
                    notNull = false;
                    break;
                }
                final CameraCharacteristics characteristics = manager.getCameraCharacteristics(str);

                final int supportLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
                if (supportLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
                    notNull = false;
                    break;
                }
            }
        }
        return notNull;
    } catch (Throwable ignore) {
        return false;
    }
}
 
Example 19
Source File: Camera2PortabilityTest.java    From Camera2 with Apache License 2.0 4 votes vote down vote up
private CameraCharacteristics buildFrameworkCharacteristics() throws CameraAccessException {
    CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
    String id = manager.getCameraIdList()[0];
    return manager.getCameraCharacteristics(id);
}
 
Example 20
Source File: Camera2Fragment.java    From 361Camera with Apache License 2.0 4 votes vote down vote up
/**
 * Sets up state related to camera that is needed before opening a {@link CameraDevice}.
 */
private boolean setUpCameraOutputs() {
    Activity activity = getActivity();
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    if (manager == null) {
        ErrorDialog.buildErrorDialog("This device doesn't support Camera2 API.").
                show(getFragmentManager(), "dialog");
        return false;
    }
    try {
        // Find a CameraDevice that supports RAW captures, and configure state.
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics
                    = manager.getCameraCharacteristics(cameraId);

            if ((!cameraId.equals(CAMERA_FRONT) && (!cameraId.equals(CAMERA_BACK))
                    || (!cameraId.equals(mCameraId)))) {
                continue;
            }
            // We only use a camera that supports RAW in this sample.
            if (!contains(characteristics.get(
                    CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES),
                    CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_RAW)) {
                continue;
            }

            StreamConfigurationMap map = characteristics.get(
                    CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

            // For still image captures, we use the largest available size.
            Size largestJpeg = Collections.max(
                    Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                    new CompareSizesByArea());

            Size largestRaw = Collections.max(
                    Arrays.asList(map.getOutputSizes(ImageFormat.RAW_SENSOR)),
                    new CompareSizesByArea());

            synchronized (mCameraStateLock) {
                // Set up ImageReaders for JPEG and RAW outputs.  Place these in a reference
                // counted wrapper to ensure they are only closed when all background tasks
                // using them are finished.
                if (mJpegImageReader == null || mJpegImageReader.getAndRetain() == null) {
                    mJpegImageReader = new RefCountedAutoCloseable<>(
                            ImageReader.newInstance(largestJpeg.getWidth(),
                                    largestJpeg.getHeight(), ImageFormat.JPEG, /*maxImages*/5));
                }
                mJpegImageReader.get().setOnImageAvailableListener(
                        mOnJpegImageAvailableListener, mBackgroundHandler);

                if (mRawImageReader == null || mRawImageReader.getAndRetain() == null) {
                    mRawImageReader = new RefCountedAutoCloseable<>(
                            ImageReader.newInstance(largestRaw.getWidth(),
                                    largestRaw.getHeight(), ImageFormat.RAW_SENSOR, /*maxImages*/ 5));
                }
                mRawImageReader.get().setOnImageAvailableListener(
                        mOnRawImageAvailableListener, mBackgroundHandler);

                mCharacteristics = characteristics;
            }
            return true;
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

    // If we found no suitable cameras for capturing RAW, warn the user.
    ErrorDialog.buildErrorDialog("This device doesn't support capturing RAW photos").
            show(getFragmentManager(), "dialog");
    return false;
}