前言
眾所周知,安卓的手電筒功能無非是開啟手機的閃光燈,既然開啟閃光燈就必須要與相機關聯(lián)。
代碼
寫了個小工具,一個文件搞定。
public class FlashUtils { private static FlashUtils utils; private static Camera camera; public static boolean mIsOpen = true; //使用單例模式在這里初始化相機 public static FlashUtils getInstance() { if (utils == null) { utils = new FlashUtils(); } try { if (camera == null) { camera = Camera.open(); } } catch (Exception e) { if (camera != null) { camera.release(); } camera = null; } return utils; } //參考二維碼工具的閃光燈 public void switchFlash() { try { Parameters parameters = camera.getParameters(); if (mIsOpen) { if (parameters.getFlashMode().equals("torch")) { return; } else { parameters.setFlashMode("torch"); } } else { if (parameters.getFlashMode().equals("off")) { return; } else { parameters.setFlashMode("off"); } } camera.setParameters(parameters); } catch (Exception e) { finishFlashUtils(); } mIsOpen = !mIsOpen; } //頁面銷毀的時候調用此方法 public void finishFlashUtils() { if (camera != null) { camera.stopPreview(); camera.release(); } camera = null; }} 6.0及其以上親測可用,需手動打開權限。
5.0以下暫未測試。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答