package com.caohuayu.flashlight;

import androidx.appcompat.app.AppCompatActivity;

import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity
    implements View.OnClickListener {

    private boolean lightStatus=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        Button btn = (Button)findViewById(R.id.btnSwitch);
        btn.setOnClickListener(this);
        //
        lightOn();
    }

    @Override
    public void onClick(View v){
        if(v.getId()==R.id.btnSwitch){
            if(lightStatus) lightOff();
            else lightOn();
        }
    }

    // 开灯
    private void lightOn(){
        try{
            CameraManager cm =
                    (CameraManager)getSystemService(CAMERA_SERVICE);
            cm.setTorchMode("0",true);
            lightStatus=true;
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    // 关灯
    private void lightOff(){
        try{
            CameraManager cm =
                    (CameraManager)getSystemService(CAMERA_SERVICE);
            cm.setTorchMode("0",false);
            lightStatus=false;
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}