我创建了一个简单的项目来玩手电筒功能。从许多不同的地方(所有这些都以相同的方式完成),我已经汇编了以下代码,但手电筒将无法启动(没有异常被提出) - 但它可以在相机工作时使用我拍了一张照片:
@Override
protected void onResume() {
super.onResume();
try {
// check flashlight support
hasFlash = 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(MainActivity.this).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
text_off = (TextView) findViewById(R.id.text_off);
text_off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
return;
}
});
getCamera();
turnOnFlash();
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "onResume Error: "+e.getMessage());
}
}
@Override
protected void onPause() {
super.onPause();
turnOffFlash();
}
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e(this.getClass().getSimpleName(), "Camera Error. Failed to Open. Error: "+e.getMessage());
}
}
}
@SuppressWarnings("deprecation")
private void turnOnFlash() {
try {
Log.d(this.getClass().getSimpleName(), "turnOnFlash CHECKPOINT ");
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
// ALSO TRIED: params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
Log.d(this.getClass().getSimpleName(), "turnOnFlash CHECKPOINT EXIT");
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "Camera Error. Failed to Open. Error: "+e.getMessage());
}
}
@SuppressWarnings("deprecation")
private void turnOffFlash() {
try {
Log.d(this.getClass().getSimpleName(), "turnOffFlash CHECKPOINT ");
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
camera.release();
isFlashOn = false;
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "Camera Error. Failed to Open. Error: "+e.getMessage());
}
}
在清单中:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
为什么这段代码没有打开/关闭手电筒?
硬件:Nexus 5
操作系统:Android Marshmallow
答案 0 :(得分:4)
我认为您缺少一些额外的代码行,这是某些设备所需要的。这三行是我到目前为止遇到的所有设备所需要的:
// will work on some devices
mCamera.setParameters(parameters);
// Needed for some devices.
mCamera.setPreviewTexture(new SurfaceTexture(0));
// Needed for some more devices.
mCamera.startPreview();
如果添加一些虚拟SurfaceTexture
,它应该有用。您还可以看到完整的代码示例here。
相机api在手机之间变化很大,而且这些手机细节记录不清。