/
FlashlightUtils.java
105 lines (94 loc) · 3 KB
/
FlashlightUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.blankj.utilcode.util;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.util.Log;
import java.io.IOException;
import static android.hardware.Camera.Parameters.FLASH_MODE_OFF;
import static android.hardware.Camera.Parameters.FLASH_MODE_TORCH;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2018/04/27
* desc : utils about flashlight
* </pre>
*/
public final class FlashlightUtils {
private static Camera mCamera;
private static SurfaceTexture mSurfaceTexture;
private FlashlightUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* Return whether the device supports flashlight.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isFlashlightEnable() {
return Utils.getApp()
.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
/**
* Return whether the flashlight is working.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isFlashlightOn() {
if (!init()) return false;
Camera.Parameters parameters = mCamera.getParameters();
return FLASH_MODE_TORCH.equals(parameters.getFlashMode());
}
/**
* Turn on or turn off the flashlight.
*
* @param isOn True to turn on the flashlight, false otherwise.
*/
public static void setFlashlightStatus(final boolean isOn) {
if (!init()) return;
final Camera.Parameters parameters = mCamera.getParameters();
if (isOn) {
if (!FLASH_MODE_TORCH.equals(parameters.getFlashMode())) {
try {
mCamera.setPreviewTexture(mSurfaceTexture);
mCamera.startPreview();
parameters.setFlashMode(FLASH_MODE_TORCH);
mCamera.setParameters(parameters);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
if (!FLASH_MODE_OFF.equals(parameters.getFlashMode())) {
parameters.setFlashMode(FLASH_MODE_OFF);
mCamera.setParameters(parameters);
}
}
}
/**
* Destroy the flashlight.
*/
public static void destroy() {
if (mCamera == null) return;
mCamera.release();
mSurfaceTexture = null;
mCamera = null;
}
private static boolean init() {
if (mCamera == null) {
try {
mCamera = Camera.open(0);
mSurfaceTexture = new SurfaceTexture(0);
} catch (Throwable t) {
Log.e("FlashlightUtils", "init failed: ", t);
return false;
}
}
if (mCamera == null) {
Log.e("FlashlightUtils", "init failed.");
return false;
}
return true;
}
}