本文实例为大家分享了android通过led实现手电筒功能的具体代码,供大家参考,具体内容如下
第一步 添加权限:
<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" />
第二步 实现手电筒工具类:
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; } }
第三步 添加手电筒按钮的触发事件(这里是在布局文件中通过onclick实现的)
/** * 打开手电筒 */ public void openFlashlight(View view) { FlashlightUtil.setSwitch() ; }