package com.rehome.sgbaxj.utils;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.os.Build;

public class FlashUtil {
    private boolean isFlashOn = false;
    private Camera camera;
    private CameraManager camManager;
    public void toggle(Context context) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                this.camManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
                String cameraId = this.camManager.getCameraIdList()[0];
                this.camManager.setTorchMode(cameraId, !this.isFlashOn);
                this.isFlashOn = !isFlashOn;
            } else {
                camera = Camera.open();
                Camera.Parameters parameters = camera.getParameters();
                if (isFlashOn) {
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                } else {
                    parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                }
                isFlashOn = !isFlashOn;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //页面销毁的时候调用此方法
    public void finishFlashUtils() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                String cameraId = camManager.getCameraIdList()[0];
                camManager.setTorchMode(cameraId, false);
                this.isFlashOn = false;
            }catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            if (camera != null) {
                camera.stopPreview();
                camera.release();
            }
            camera = null;
        }
    }
}
