我正在使用自定义相机创建一个 Android 应用程序,并且正在切换到新的 camera2 API。我有一个按钮,可以在后置摄像头打开时打开和关闭闪光灯(无需停止摄像头,就像任何经典的相机应用程序一样)。
当我点击 flash 图标时,什么也没有发生,这就是 logcat 返回的内容:
D/ViewRootImpl: ViewPostImeInputStage processPointer 0
D/ViewRootImpl: ViewPostImeInputStage processPointer 1
我不知道为什么它不起作用。这是代码:
我有一个RecordVideoActivity
使用RecordVideoFragment
. 这是包含 flash 按钮代码的片段的 XML 部分:
<ImageButton
android:id="@+id/button_flash"
android:src="@drawable/ic_flash_off"
android:layout_alignParentLeft="true"
style="@style/actions_icons_camera"
android:onClick="actionFlash"/>
和Java代码:
ImageButton flashButton;
private boolean hasFlash;
private boolean isFlashOn = false;
随着在onViewCreated
:
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
...
[some code]
...
// Flash on/off button
flashButton = (ImageButton) view.findViewById(R.id.button_flash);
// Listener for Flash on/off button
flashButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionFlash();
}
});
这是actionFlash()
函数定义:
private void actionFlash() {
/* First check if device is supporting flashlight or not */
hasFlash = getActivity().getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
// device doesn't support flash
// Show alert message and close the application
AlertDialog alert = new AlertDialog.Builder(this.getActivity())
.create();
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
return;
}
else { // the device support flash
CameraManager mCameraManager = (CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
try {
String mCameraId = mCameraManager.getCameraIdList()[0];
if (mCameraId.equals("1")) { // currently on back camera
if (!isFlashOn) { // if flash light was OFF
// Turn ON flash light
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
}
} catch (Exception e) {
e.printStackTrace();
}
// Change isFlashOn boolean value
isFlashOn = true;
// Change button icon
flashButton.setImageResource(R.drawable.ic_flash_off);
} else { // if flash light was ON
// Turn OFF flash light
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
}
} catch (Exception e) {
e.printStackTrace();
}
// Change isFlashOn boolean value
isFlashOn = false;
// Change button icon
flashButton.setImageResource(R.drawable.ic_flash_on);
}
}
} catch (CameraAccessException e) {
Toast.makeText(getActivity(), "Cannot access the camera.", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
}
知道有什么问题吗?
(我已经看过这个问题,但它没有解决我的问题)
非常感谢您的帮助。这真让我抓狂。