android realizes flashlight function through led
- 2021-11-13 02:44:11
- OfStack
This article example for everyone to share android through led to achieve flashlight function of the specific code, for your reference, the specific content is as follows
Step 1 Add permissions:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.flash" />
Step 2 implements the flashlight tool class:
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.AsyncTask;
/**
*Caution: On some devices, this method may take a long time to complete. It is best
*to call this method from a worker thread (possibly using android.os.AsyncTask) to
*avoid blocking the main application UI thread.
*/
public class FlashlightUtil extends AsyncTask<String, String, String> {
private Camera camera;
private int cameraId = 0; // This function is not practical at present, so it will not be implemented here , But it cannot be deleted
private Parameters parameters;
public boolean isTorch = false;
private boolean canFinish = false;
private static FlashlightUtil flashlightUtil;
private FlashlightUtil() {
}
/**
* Set the flashlight switch, turn on or off the flashlight, and set the opposite state according to the state of the flashlight void 2016 Year 1 Month 12 Day
*/
public static void setSwitch() {
if (null == flashlightUtil) {
flashlightUtil = new FlashlightUtil();
flashlightUtil.execute("");
}
flashlightUtil.setONOFF();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
while (!canFinish) {
if (null == camera) {
camera = Camera.open(cameraId);
}
parameters = camera.getParameters();
if (isTorch) {
if (parameters.getFlashMode().equals(Parameters.FLASH_MODE_OFF)) {
// Turn on the spotlight
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();
}
} else {
if (parameters.getFlashMode().equals(
Parameters.FLASH_MODE_TORCH)) {
// Turn off the spotlight
camera.stopPreview(); // Turn off the lights
camera.release(); // Turn off the camera
camera = null;
}
}
}
return null;
}
/**
* This feature is temporarily turned off
* @hide
*/
public FlashlightUtil setCameraId(int cameraId) {
this.cameraId = cameraId;
return flashlightUtil;
}
/**
* Turn on and off the flashlight, default 1 The second is open 2016 Year 1 Month 12 Day
*/
private void setONOFF() {
isTorch = !isTorch;
}
}
Step 3 Add the trigger event of the flashlight button (this is implemented in the layout file through onclick)
/**
* Turn on a flashlight
*/
public void openFlashlight(View view) {
FlashlightUtil.setSwitch() ;
}
The flashlight function is relatively simple, and it is opened and closed in one step.