Android5.0 以后已经抛弃了Camer 相关的API,改用新的API接口CamerManager.
1. Anf文件
<!--开启闪关灯的权限-->
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.autofocus"/>
2. 代码文件
- 在onCreate方法中初始化
//6.0及以上系统开启闪光灯操作
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());
}
- 找到控件设置点击事件
case R.id.iv_flashlight:
iv_flashlight.startAnimation(animation);
if (!isOpen) {
if (isLOLLIPOP()) {
try {
manager.setTorchMode("0", true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}else{
camera = Camera.open();
camera.startPreview();
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
}
} else {
if (isLOLLIPOP()) {
try {
manager.setTorchMode("0", false);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}else{
parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
}
}
- 判断Android系统版本是否 >= LOLLIPOP(API21)
/**
* 判断Android系统版本是否 >= LOLLIPOP(API21)
*
* @return boolean
*/
private boolean isLOLLIPOP() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return true;
} else {
return false;
}
}
如有疑问请戳这里 東方月初
网友评论