Use the device's flash unit on Android SDK (Kotlin/Java)

Enabling the device's flash unit during an AR session can help improve visibility.

Check that the current camera configuration supports flash

Not all camera configurations support enabling a flash unit. Before enabling the flash or offering users the option to enable the flash, ensure that the flash unit is available for the active camera configuration:

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 

Enable the flash unit

Enable the flash unit by configuring the AR session with 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 
  
 }) 
 } 

Disable the flash unit

Disable the flash unit by configuring the AR session with 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 
  
 }) 
Design a Mobile Site
View Site in Mobile | Classic
Share by: