Android 使用 Camera2 以编程方式打开/关闭相机闪光灯 [英] Android Turn on/off Camera Flash Programmatically with Camera2

查看:105
本文介绍了Android 使用 Camera2 以编程方式打开/关闭相机闪光灯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个用作手电筒的简单应用程序.我需要能够使用 Camera2 API 从应用程序中的按钮打开和关闭闪光灯,因为旧的相机 API 出现错误.我想使用手电筒"手电筒,无需打开相机即可打开闪光灯.我知道这是可能的,因为许多手机在快速设置菜单中都打开/关闭了闪光灯,但我找不到任何有关如何执行此操作的代码或教程.

I am making a simple application that acts as a flashlight. I need to be able to turn on and off the flash from a button in the application with the Camera2 API, as I get errors with the old camera API. I would like to use a "torch" flashlight, where the camera doesn't have to open in order for the flash to turn on. I know it's possible, as lots of phones have a flash on/off in the quick settings menu, but I can't find any code or tutorials about how to do this.

代码:

Camera cam = Camera.open();     
Parameters p = cam.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(p);
cam.startPreview();

我在运行 Android 6.0.1 的 Nexus 6P 上运行.

I am running on a Nexus 6P with Android 6.0.1.

我需要使用 Camera2 API.我还没有找到一个很好的教程,在得到答案后,我将在这里以 Q/A 格式创建一个.

I need to use the Camera2 API. I haven't found a good tutorial for this yet, and after getting an answer, I will create one in Q/A format on here.

推荐答案

我会联系 Android 开发人员.关于 CameraManager 的文档,因为需要更多代码,但这是在 API 21 以上的 API 中激活相机上的 Flash 的基本代码.

I'll be addressing you to the Android Dev. documentation about the CameraManager since more code will be required but this is the basic code to activate the Flash on the camera in API's above 21.

CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = camManager.getCameraIdList()[0]; // Usually front camera is at 0 position.
camManager.setTorchMode(cameraId, true);

Android CameraManager 文档.

Android.hardware.camera2 文档.

要记住的重要一点是,您需要使用 try/catch 来丢弃可能的错误,当然还要检查当前没有其他更高优先级的应用程序正在使用相机.

very important thing to remember that you will need to use try/catch to discard possible errors and ofcourse check that no other higher priority application is using the camera at the moment.

这篇关于Android 使用 Camera2 以编程方式打开/关闭相机闪光灯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆