preface
The company is engaged in system application development, and there is a need to develop a flashlight, which will show the switch status. At the beginning, Baidu did not find the interface for monitoring the status of external apps calling the flashlight. However, I found that the status of the flashlight switch on the status bar was the same as the current status of the flashlight. When I turned on the flashlight in my app, the status bar showed that the flashlight status was on, so I found its implementation.
StatusBar flashlight implementation
Specific see frameworks/base/packages/SystemUI/SRC/com/android/SystemUI/statusbar/policy/FlashlightControllerImpl. Java code
public class FlashlightControllerImpl implements FlashlightController {
private static final String TAG = "FlashlightController";
private final CameraManager mCameraManager;
private Handler mHandler;
private String mCameraId;
private boolean mTorchAvailable;
public FlashlightControllerImpl(Context context) {
mContext = context;
/ / code 1
mCameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
tryInitCamera();
}
private void tryInitCamera(a) {
try {
mCameraId = getCameraId();
} catch (Throwable e) {
Log.e(TAG, "Couldn't initialize.", e);
return;
}
if(mCameraId ! =null) {
ensureHandler();
/ / code 2mCameraManager.registerTorchCallback(mTorchCallback, mHandler); }}/ / code 3
public void setFlashlight(boolean enabled) {
boolean pendingError = false;
synchronized (this) {
if (mCameraId == null) return;
if(mFlashlightEnabled ! = enabled) { mFlashlightEnabled = enabled;try {
mCameraManager.setTorchMode(mCameraId, enabled);
} catch (CameraAccessException e) {
Log.e(TAG, "Couldn't set torch mode", e);
mFlashlightEnabled = false;
pendingError = true; }}}... }// Check whether there is a flashlight
public boolean hasFlashlight(a) {
/ / code 4
return mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}
private synchronized void ensureHandler(a) {
if (mHandler == null) {
HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mHandler = newHandler(thread.getLooper()); }}private final CameraManager.TorchCallback mTorchCallback =
new CameraManager.TorchCallback() {
@Override
public void onTorchModeUnavailable(String cameraId) {
if (TextUtils.equals(cameraId, mCameraId)) {
setCameraAvailable(false); }}@Override
public void onTorchModeChanged(String cameraId, boolean enabled) {
5 / / code}}; }Copy the code
- Code 1 obtains the CamreaManager service
- Code 2, code 5: Code 2 to register the monitoring of the flashlight, code 5 to monitor the flashlight switch status
- Code 3 determines whether the device supports the flashlight function
- Code 4 sets the flashlight
The above code moved to their own application, you can achieve the state of the flashlight monitoring.