Android realizes flashlight function through LED
•
Android
This example shares the specific code for Android to realize the flashlight function through LED for your reference. The specific contents are 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 realize flashlight tools:
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; // 此功能目前不实用,这里不做实现 , 但不能删除 private Parameters parameters; public boolean isTorch = false; private boolean canFinish = false; private static FlashlightUtil flashlightUtil; private FlashlightUtil() { } /** * 设置手电筒开关,打开或关闭手电筒,根据手电筒的状态来设置相反的状态 void 2016年1月12日 */ 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)) { // 打开镁光灯 parameters.setFlashMode(Parameters.FLASH_MODE_TORCH); camera.setParameters(parameters); camera.startPreview(); } } else { if (parameters.getFlashMode().equals( Parameters.FLASH_MODE_TORCH)) { // 关闭镁光灯 camera.stopPreview(); // 关掉亮灯 camera.release(); // 关掉照相机 camera = null; } } } return null; } /** * 此功能暂时关闭 * @hide */ public FlashlightUtil setCameraId(int cameraId) { this.cameraId = cameraId; return flashlightUtil; } /** * 打开关闭手电筒,默认第一次为打开 2016年1月12日 */ private void setONOFF() { isTorch = !isTorch; } }
Step 3: add the trigger event of flashlight button (this is implemented through onclick in the layout file)
/** * 打开手电筒 */ public void openFlashlight(View view) { FlashlightUtil.setSwitch() ; }
The function of flashlight is relatively simple. Here, one-step opening and closing is realized.
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码