在 Android SDK (Kotlin/Java) 上使用设备的闪存单元

在 AR 会话期间启用设备的闪光灯单元有助于提高可见度。

检查当前的相机配置是否支持闪光灯

并非所有相机配置都支持启用闪光灯。在启用闪光灯或向用户提供启用闪光灯的选项之前,请确保闪光灯单元适用于当前的相机配置:

Java

boolean flashAvailable;
try {
  CameraManager cameraManager =
      (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);

  CameraCharacteristics characteristics =
      cameraManager.getCameraCharacteristics(session.getCameraConfig().getCameraId());
  flashAvailable = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
} catch (Exception e) {
  flashAvailable = false;
}

Kotlin

val flashAvailable =
  runCatching {
      val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
      val characteristics = cameraManager.getCameraCharacteristics(session.cameraConfig.cameraId)
      characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)
    }
    .getOrNull() ?: false

启用闪光灯装置

配置 AR 会话以启用闪存装置 Config.FlashMode.TORCH:

Java

if (flashAvailable) {
  Config config = session.getConfig();
  config.setFlashMode(Config.FlashMode.TORCH);
  session.configure(config);
}

Kotlin

if (flashAvailable) {
  session.configure(session.config.apply { flashMode = Config.FlashMode.TORCH })
}

停用闪光灯

通过配置 AR 会话来停用闪存装置 Config.FlashMode.OFF:

Java

Config config = session.getConfig();
config.setFlashMode(Config.FlashMode.OFF);
session.configure(config);

Kotlin

session.configure(session.config.apply { flashMode = Config.FlashMode.OFF })