我做了一个简单的FlashLight应用程序。运行正常,但是有一个错误。启动应用程序后的第一次第一次按下向下按钮时,它不会启动手电筒。当我再次按下按钮时,它将启动手电筒。
帮我解决这个问题。谢谢!
问题:第一次按下按钮时Flashlight无法启动。
private Camera camera;
private ImageButton flashlightButton;
private TextView Status;
private static final int CAMERA_REQUEST = 123;
boolean hasCameraFlash = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},CAMERA_REQUEST);
Status = findViewById(R.id.Status);
flashlightButton = findViewById(R.id.flashlight_button);
flashlightButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (hasCameraFlash){
if (Status.getText().toString().contains("ON")){
Status.setText("OFF");
flashlightOff();
} else {
Status.setText("ON");
flashlightOn();
}
}else{
Toast.makeText(MainActivity.this, "No Flash Available on your device",Toast.LENGTH_SHORT).show();
}
}
});
}
private void flashlightOn(){
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId,true);
flashlightButton.setImageResource(R.drawable.flashlight_on);
} catch (CameraAccessException e) {
}
}
private void flashlightOff(){
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String camerid = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(camerid,false);
flashlightButton.setImageResource(R.drawable.flashlight_off);
} catch (CameraAccessException e){
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case CAMERA_REQUEST:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
hasCameraFlash = getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}else{
Toast.makeText(MainActivity.this, "Permission Denied for the Camera", Toast.LENGTH_SHORT).show();
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (camera != null) {
camera.stopPreview();
camera.setPreviewCallback(null);
camera.release();
camera = null;
}
}
}
答案 0 :(得分:0)
使用权限
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature
android:name="android.hardware.camera.flash"
android:required="false" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
代码:
Parameters p = mCamera.getParameters();
Camera mCamera = Camera.open();
p = mCamera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_ON);
mPreview = new CameraPreview(mContext, mCamera);
mCamera.startPreview();
答案 1 :(得分:0)
在您的代码中未发现错误。也许在您的XML布局文件中,按钮具有如下属性:
android:onClick="onClick" //delete if such line exists
另一个可能性是按钮具有如下属性:
android:focusableInTouchMode="true" //delete if such line exists