1. 程式人生 > >Android控制手電筒程式碼,簡單易用,不需要任何許可權

Android控制手電筒程式碼,簡單易用,不需要任何許可權

1.控制手電筒開關的工具類:

public class FlashUtils {
    private CameraManager manager;
    private Camera mCamera = null;
    private Context context;
    private boolean status = false;//記錄手電筒狀態
FlashUtils(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            manager 
= (CameraManager) context.getSystemService(Context.CAMERA_SERVICE); } this.context = context; } //開啟手電筒 public void open() { if(status){//如果已經是開啟狀態,不需要開啟 return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { manager.setTorchMode("0"
, true); } catch (Exception e) { e.printStackTrace(); } } else { PackageManager packageManager = context.getPackageManager(); FeatureInfo[] features = packageManager.getSystemAvailableFeatures(); for (FeatureInfo featureInfo : features) { if
(PackageManager.FEATURE_CAMERA_FLASH.equals(featureInfo.name)) { // 判斷裝置是否支援閃光燈 if (null == mCamera) { mCamera = Camera.open(); } Camera.Parameters parameters = mCamera.getParameters(); parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); mCamera.setParameters(parameters); mCamera.startPreview(); } } } status = true;//記錄手電筒狀態為開啟 } //關閉手電筒 public void close() { if(!status){//如果已經是關閉狀態,不需要開啟 return; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { try { manager.setTorchMode("0", false); } catch (CameraAccessException e) { e.printStackTrace(); } } else { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } } status = false;//記錄手電筒狀態為關閉 } //改變手電筒狀態 public void converse(){ if(status){ close(); }else{ open(); } } }

2.使用方法:

FlashUtils utils = new FlashUtils(this);
utils.open();//開啟手電筒
//        utils.close();//關閉手電筒

3.示例程式已上傳: