我一直在尝试在我的代码扫描应用程序中实现打开/关闭手电筒,但我没有找到解决我面临的问题的好方法。
负责扫描代码的代码:( MainActivity.kt)
val clipboard = getSystemService(context, ClipboardManager::class.java)
val compoundBarcodeView = remember {
CompoundBarcodeView(context).apply {
val capture = CaptureManager(activity, this)
capture.initializeFromIntent(
Intent(Intent.ACTION_MEDIA_SCANNER_STARTED).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
null
)
this.setStatusText("")
capture.decode()
this.resume()
this.decodeSingle { result ->
result.text?.let { barCodeOrQr ->
contentOfScannedCode = barCodeOrQr
showPopup = true // basically this takes care of displaying a popup message, you do not have to add this
}
}
}
}
后来这被使用:
if(!showPopup) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { compoundBarcodeView },
)
Row(
Modifier
.padding(15.dp)
.border(
width = 1.dp,
color = colorResource(id = R.color.button_background_light_blue),
shape = RoundedCornerShape(10.dp)
)
){
IconButton(onClick = {}) {
Icon(painterResource(id = R.drawable.ic_photo), contentDescription = "scan code from image", tint = colorResource(
id = R.color.button_background_light_blue
))
}
IconButton(onClick = {
currentFlashlightMode = if(currentFlashlightMode == 0) {
Camera(context).startFlashlight()
1
} else {
Camera(context).stopFlashlight()
0
}
}) {
Icon(painterResource(id = R.drawable.ic_flashlight), contentDescription = "turn on flashlight", tint = colorResource(
id = R.color.button_background_light_blue
))
}
}
}
你可以猜到我想在用户点击手电筒图标时切换手电筒状态,应该处理的代码是:
class Camera(private val context: Context) {
fun startFlashlight(){
val canUseFlashlight = context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
var cameraId = ""
if(!canUseFlashlight){
Toast.makeText(context, "your device doesn't support flash light", Toast.LENGTH_SHORT).show()
} else {
val camManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
cameraId = camManager.cameraIdList[0]
} catch (e: CameraAccessException) {
logcat{e.printStackTrace().toString()}
}
try {
logcat { cameraId }
camManager.setTorchMode(cameraId, true)
} catch (e: CameraAccessException) {
logcat{e.printStackTrace().toString()}
}
}
}
fun stopFlashlight(){
val canUseFlashlight = context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
var cameraId = ""
if(!canUseFlashlight){
Toast.makeText(context, "your device doesn't support flash light", Toast.LENGTH_SHORT).show()
} else {
val camManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
cameraId = camManager.cameraIdList[0]
} catch (e: CameraAccessException) {
logcat{e.printStackTrace().toString()}
}
try {
logcat { cameraId }
camManager.setTorchMode(cameraId, false)
} catch (e: CameraAccessException) {
logcat{e.printStackTrace().toString()}
}
}
}
}
如果我停止相机,打开/关闭手电筒并恢复相机进度,它可能会起作用,但这似乎对用户不太友好,所以我尝试同时使用手电筒和相机,结果导致
由于现有相机用户(代码 7),相机“0”的手电筒不可用
任何想法如何解决这个问题?