Android6.0 已经抛弃了Camer 相关的API,改用新的API接口CamerManager,下面给出使用的简单实例
package com.inper.duqiang.slashlight;import android.app.Activity;import android.content.Context;import android.hardware.Camera;import android.hardware.camera2.CameraAccessException;import android.hardware.camera2.CameraManager;import android.os.Build;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.CompoundButton;import android.widget.ToggleButton;public class MainActivity extends Activity { private CameraManager manager; private Camera camera = null; private Camera.Parameters parameters = null; public static boolean kaiguan = true; // 定义开关状态,状态为false,打开状态,状态为true,关闭状态 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); super.onCreate(savedInstanceState); manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { String [] camerList = manager.getCameraIdList(); for (String str:camerList ) { Log.d("List",str); } } catch (CameraAccessException e) { Log.e("error",e.getMessage()); } Button open_btn = (Button) findViewById(R.id.open_btn); open_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isLOLLIPOP()) { try { manager.setTorchMode("0", true); } catch (CameraAccessException e) { e.printStackTrace(); } } } }); Button close_btn = (Button) findViewById(R.id.close_btn); close_btn.setOnClickListener(closeOnClickListener); ToggleButton toggle_btn = (ToggleButton) findViewById(R.id.toggle_btn); toggle_btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { try { manager.setTorchMode("1", isChecked); } catch (CameraAccessException e) { e.printStackTrace(); } } }); } private View.OnClickListener closeOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (isLOLLIPOP()) { try { manager.setTorchMode("0", false); } catch (CameraAccessException e) { e.printStackTrace(); } } } }; /** * 判断Android系统版本是否 >= LOLLIPOP(API21) * * @return boolean */ private boolean isLOLLIPOP() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return true; } else { return false; } }}
Layout的布局
Anf文件