Android 控制闪光灯

首先闪光灯可以用android.hardware.camera来控制。

1.添加权限

1 <uses-permission android:name="android.permission.FLASHLIGHT" />
2 
3 <uses-permission android:name="android.permission.CAMERA"/>
4 
5 <uses-feature android:name="android.hardware.camera" />

 

2.获得Camera对象,通过Camera.open()开启摄像头。

Camera camera = Camera.open();

 

3.打开闪光灯

 1 public static void turnLightOn(Camera mCamera) {
 2   if (mCamera == null) {
 3    return;
 4   }
 5   Parameters parameters = mCamera.getParameters();
 6   if (parameters == null) {
 7    return;
 8   }
 9     List<String> flashModes = parameters.getSupportedFlashModes();
10     // Check if camera flash exists
11     if (flashModes == null) {
12        // Use the screen as a flashlight (next best thing)
13        return;
14     }
15     String flashMode = parameters.getFlashMode();
16 if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) { 17 // Turn on the flash 18 if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) { 19 parameters.setFlashMode(Parameters.FLASH_MODE_TORCH); 20 mCamera.setParameters(parameters); 21 } else { 22 } 23 } 24 }

4.关闭闪光灯

 1 public static void turnLightOff(Camera mCamera) {
 2   if (mCamera == null) {
 3     return;
 4   }
 5   Parameters parameters = mCamera.getParameters();
 6   if (parameters == null) {
 7     return;
 8   }
 9   List<String> flashModes = parameters.getSupportedFlashModes();
10   String flashMode = parameters.getFlashMode();
11   // Check if camera flash exists
12   if (flashModes == null) {
13     return;
14   }
15   if (!Parameters.FLASH_MODE_OFF.equals(flashMode)) {
16   // Turn off the flash
17    if (flashModes.contains(Parameters.FLASH_MODE_OFF)) {
18      parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
19      mCamera.setParameters(parameters);
20    } else {
21          Log.e(TAG, "FLASH_MODE_OFF not supported");
22       }
23     }
24 }

5.关闭闪光灯后记得释放Camear对象

camera.release();

 

源代码:Flashlight.7z

你可能感兴趣的:(android)