我正在尝试制作一个火炬之光应用程序,但我无法正常启用它。我使用以下逻辑将其打开。请让我知道我哪里出错了。当我在我的Android手机上运行它时,它运行正常,但手电筒没有启动。
if (count[0] == 0) {
count[0] = 1;
((TransitionDrawable) imageView.getDrawable()).startTransition(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null; // Usually back camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true); //Turn ON
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
} else {
count[0] = 0;
((TransitionDrawable) imageView.getDrawable()).reverseTransition(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
CameraManager camManager1 = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null; // Usually back camera is at 0 position.
try {
cameraId = camManager1.getCameraIdList()[0];
camManager1.setTorchMode(cameraId, false); //Turn ON
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
您编写的代码在Android Marshmallow +上完全正常运行。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
此行检查您运行该应用的Android版本。它仅在Android版本6+(API级别23 +)上执行if
块内的代码。
您需要使用较旧的方式添加else
部分来启用手电筒:How to turn on camera flash light programmatically in Android?