Android实现一个简单的手电筒

添加手机权限

    
    
    
    

布局

    

代码

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    private Button btn_open;
    private boolean status=false;
    private CameraManager cm;
    private Camera camera;
    Camera.Parameters parameters;
    MainActivity instance;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance=this;
        btn_open= (Button) findViewById(R.id.btn_open);
        btn_open.setText("open");
        cm= (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        camera=Camera.open();
        btn_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!status){
                    btn_open.setText("close");
                    status=true;
                    new Thread(new TurnOnLight()).start();
                }else{
                    parameters=camera.getParameters();
                    instance.parameters.setFlashMode("off");
                    camera.setParameters(instance.parameters);
                    btn_open.setText("open");
                    status=false;
                }
            }
        });
        }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        camera.stopPreview();
        camera.release();
        camera = null;
    }


    private class TurnOnLight implements Runnable {
        @Override
        public void run() {
            instance.parameters=instance.camera.getParameters();
            instance.parameters.setFlashMode("torch");
            instance.camera.setParameters(instance.parameters);
        }
    }
}

总结:

声明完调用系统硬件后,想要使用闪光灯则要创建CameraManager ,Camera,以及Camera.Parameters对象。顾名思义,前面两个不用解释,Parameters表示相机服务的参数(例如聚焦,闪关灯,滤镜等等的一些相关配置)
具体操作:
CameraManager cm= (CameraManager)getSystemService(Context.CAMERA_SERVICE)
Camera camera=Camera.open();
Camera.Parameters parameter=camera.getParameters();
//打开闪光灯
parameters.setFlashMode(“torch”);//打开
camera.setParameters(paramsters);
//关闭闪光灯
parameters.setFlashMode(“off”);//关闭
camera.setParameters(paramsters);


你可能感兴趣的:(Android实现一个简单的手电筒)