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

1.添加权限

 <uses-permission android:name="android.permission.FLASHLIGHT" />

 <uses-permission android:name="android.permission.CAMERA"/>

 <uses-feature android:name="android.hardware.camera" />

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

Camera camera = Camera.open();

3.打开闪光灯

 public static void turnLightOn(Camera mCamera) {
  if (mCamera == null) {
3    return;
  }
  Parameters parameters = mCamera.getParameters();
6   if (parameters == null) {
7    return;
8   }
List<String> flashModes = parameters.getSupportedFlashModes();
// Check if camera flash exists
if (flashModes == null) {
// Use the screen as a flashlight (next best thing)
return;
}
String flashMode = parameters.getFlashMode();
if (!Parameters.FLASH_MODE_TORCH.equals(flashMode)) {
// Turn on the flash
18 if (flashModes.contains(Parameters.FLASH_MODE_TORCH)) {
19 parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(parameters);
} else {
}
}
24 }

4.关闭闪光灯

 public static void turnLightOff(Camera mCamera) {
  if (mCamera == null) {
    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 {
Log.e(TAG, "FLASH_MODE_OFF not supported");
}
}
}

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

camera.release();

源代码:Flashlight.7z

04-14 03:59