我一直在为安卓制作手电筒应用程序,并遇到了几个问题,到目前为止已经解决了它们。但是现在,当我运行该应用程序时,它会在我的HTC One上加载并正常运行,直到我第四次按下手电筒电源按钮。我可以按一次它就会打开。我再按第二次它就会关闭。我再按第三次它就会重新打开。我按第四次它就无法关闭?求助?
public class MainActivity extends Activity {
ImageButton powerButton;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
@TargetApi(Build.VERSION_CODES.ECLAIR)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
powerButton = (ImageButton) findViewById(R.id.power_button);
hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Notice");
alert.setMessage("I'm sorry, your device doesn't support flashlight!");
alert.setButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
return;
}
getCamera();
toggleButtonImage();
powerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else {
turnOnFlash();
}
}
});
}
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Failed to open camera. Alert: ", e.getMessage());
}
}
}
public void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
toggleButtonImage();
}
}
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
toggleButtonImage();
}
}
private void toggleButtonImage(){
if(isFlashOn){
powerButton.setImageResource(R.drawable.flashlight_on);
}else{
powerButton.setImageResource(R.drawable.flashlight_off);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
super.onPause();
turnOffFlash();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onResume() {
super.onResume();
if(hasFlash)
turnOffFlash();
}
@Override
protected void onStart() {
super.onStart();
getCamera();
}
@Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
' 清单文件 - http://pastebin.com/Tw6LTemP ' 主活动布局文件 - http://pastebin.com/Tga1agN7