1.控制手電筒開關(guān)的工具類:
public class FlashUtils {
? ? private CameraManager manager;
? ? private Camera mCamera = null;
? ? private Context context;
? ? private boolean status = false;//記錄手電筒狀態(tài)
? ? 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){//如果已經(jīng)是打開狀態(tài),不需要打開
? ? ? ? ? ? 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)) { // 判斷設(shè)備是否支持閃光燈
? ? ? ? ? ? ? ? ? ? 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;//記錄手電筒狀態(tài)為打開
? ? }
? ? //關(guān)閉手電筒
? ? public void close() {
? ? ? ? if(!status){//如果已經(jīng)是關(guān)閉狀態(tài),不需要打開
? ? ? ? ? ? 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;//記錄手電筒狀態(tài)為關(guān)閉
? ? }
? ? //改變手電筒狀態(tài)
? ? public void converse(){
? ? ? ? if(status){
? ? ? ? ? ? close();
? ? ? ? }else{
? ? ? ? ? ? open();
? ? ? ? }
? ? }
}
2.使用方法:
FlashUtils utils = new FlashUtils(this);
? ? ? ? utils.open();//打開手電筒
//? ? ? ? utils.close();//關(guān)閉手電筒
3.示例程序已上傳:
https://github.com/wkxjc/FlashlightStudy