查了很多资料,其他博客大多都是介绍以前的的方案,基于9.0系统的基本没有找到,要么就不全,特别是获取手电筒状态的资料,下面就大致介绍一下:
打开和关闭的方法是:toggleLight
获取手电筒状态的通过回调方法:mTorchCallback(这就是为什么进入页面就需要注册该回调)
private CameraManager mCameraManager;
public void initData() {
//ivFlashlight是界面上的imageview控件
ivFlashlight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toggleLight(!isFlashLightOn);
}
});
//获取CameraManager
if(mCameraManager == null){
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
}
mCameraManager.registerTorchCallback(mTorchCallback, null);
}
//callback成员变量初始化
private CameraManager.TorchCallback mTorchCallback = new CameraManager.TorchCallback() {
@Override
public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) {
super.onTorchModeChanged(cameraId, enabled);
Log.e(TAG, "onTorchModeChanged cameraId=" + cameraId + ";enabled=" + enabled);
isFlashLightOn = enabled;
ivFlashlight.setIcon(enabled ? MaterialDrawableBuilder.IconValue.FLASHLIGHT : MaterialDrawableBuilder.IconValue.FLASHLIGHT_OFF);
}
};
public void toggleLight(boolean OPEN) {
try {
//获取当前手机所有摄像头设备ID
String[] ids = mCameraManager.getCameraIdList();
for (String id : ids) {
CameraCharacteristics c = mCameraManager.getCameraCharacteristics(id);
//查询该摄像头组件是否包含闪光灯
Boolean flashAvailable = c.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
/*
* 获取相机面对的方向
* CameraCharacteristics.LENS_FACING_FRONT 前置摄像头
* CameraCharacteristics.LENS_FACING_BACK 后只摄像头
* CameraCharacteristics.LENS_FACING_EXTERNAL 外部的摄像头
*/
Integer lensFacing = c.get(CameraCharacteristics.LENS_FACING);
if (flashAvailable != null && flashAvailable
&& lensFacing != null && lensFacing == CameraCharacteristics.LENS_FACING_BACK) {
//打开或关闭手电筒
mCameraManager.setTorchMode(id, OPEN);
break;
}
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mCameraManager != null && mTorchCallback != null){
mCameraManager.unregisterTorchCallback(mTorchCallback);
}
}