0

嘿伙计们,我正在使用在线教程开发手电筒应用程序。我对应用程序进行了一些更改。如果用户进入主屏幕或锁定屏幕,我希望手电筒一直亮着。但是,当我这样做并打开默认相机应用程序,然后再次打开我的手电筒应用程序时,手电筒不再工作了。

重现错误的步骤:

  1. 打开应用程序(自动打开闪光灯)
  2. 按主屏幕按钮(闪光灯常亮)
  3. 打开默认相机应用程序(闪光灯关闭)
  4. 再次打开手电筒应用程序(开/关按钮不起作用,闪光灯保持关闭)

我的代码:

package ali.simpleflaslight;

import android.app.Activity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

  ImageButton btnSwitch;
  private Camera camera;
  private boolean isFlashOn;
  private boolean hasFlash;
  Parameters params;
  MediaPlayer mp;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      try {
        //================================== Flash Switch Button =============================//
        btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);
        //================================== First Check =====================================//
        hasFlash = getApplicationContext().getPackageManager()
          .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

        if (!hasFlash) {
          AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
            .create();
          alert.setTitle("Error");
          alert.setMessage("Sorry, your device doesn't support a flashlight!");
          alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              // closing the application
              finish();
            }
          });
          alert.show();
          return;
        }
        getCamera();
        toggleButtonImage();
        btnSwitch.setOnClickListener(new View.OnClickListener() {@
          Override
          public void onClick(View v) {
            if (isFlashOn) {
              // turn off flash
              turnOffFlash();
            } else {
              // turn on flash
              turnOnFlash();
            }
          }
        });
      } catch (Exception e) {}
    }
    //====================================== Getting Camera Parameters ===========================//
  private void getCamera() {
      try {
        if (camera == null) {
          try {
            camera = Camera.open();
            params = camera.getParameters();
          } catch (Exception e) {}
        }
      } catch (Exception e) {}
    }
    //====================================== Turning On Flash ====================================//
  private void turnOnFlash() {
      try {
        if (!isFlashOn) {
          if (camera == null || params == null) {
            return;
          }
          //Play Sound
          playSound();

          params = camera.getParameters();
          params.setFlashMode(Parameters.FLASH_MODE_TORCH);
          camera.setParameters(params);
          camera.startPreview();
          isFlashOn = true;

          //Changing Button/Switch Image
          toggleButtonImage();
        }
      } catch (Exception e) {}
    }
    //====================================== Turning Off Flash ===================================//
  private void turnOffFlash() {
      try {
        if (isFlashOn) {
          if (camera == null || params == null) {
            return;
          }
          //Play Sound
          playSound();

          params = camera.getParameters();
          params.setFlashMode(Parameters.FLASH_MODE_OFF);
          camera.setParameters(params);
          camera.stopPreview();
          isFlashOn = false;

          //Changing Button/Switch Image
          toggleButtonImage();
        }
      } catch (Exception e) {}
    }
    //====================================== Toggle Image ========================================//
  private void toggleButtonImage() {
      try {
        if (isFlashOn) {
          btnSwitch.setImageResource(R.drawable.btn_switch_on);
        } else {
          btnSwitch.setImageResource(R.drawable.btn_switch_off);
        }
      } catch (Exception e) {}
    }
    //====================================== Play Sound ==========================================//
  private void playSound() {
    try {
      if (isFlashOn) {
        mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
      } else {
        mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
      }
      mp.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
          // TODO Auto-generated method stub
          mp.release();
        }
      });
      mp.start();
    } catch (Exception e) {}
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }

  @Override
  protected void onPause() {
    super.onPause();
    //================================== On Pause Turn Off The Flash =========================//
    //turnOffFlash();

  }

  @Override
  protected void onRestart() {
    super.onRestart();
  }

  @Override
  protected void onResume() {
    super.onResume();
    //================================== On Resume Turn On The Flash =========================//
    if (hasFlash) {
      turnOnFlash();
    }
  }

  @Override
  protected void onStart() {
    super.onStart();
    //================================== On Starting The App Get The Camera Params============//
    getCamera();
  }

  @Override
  protected void onStop() {
    super.onStop();
    // on stop release the camera
    /*if (camera != null) {
        camera.release();
        camera = null;
    }*/
  }
}

在我在 onStop 中注释代码后,该应用程序停止工作。令人惊讶的是,Playstore 中所有支持背景闪光灯的顶级手电筒应用程序,如果按照上述步骤操作,它们就会停止工作。但是对我来说,我猜这个应用程序只是停止做任何事情,因为我尝试了流行语。有什么解决办法吗?

编辑:

将 getCamera 放在 onResume 之前后出错(并执行与上述相同的步骤):

05 - 08 19: 41: 10.955 4378 - 4378 / ali.simpleflaslight W / System.err﹕ java.lang.RuntimeException: getParameters failed(empty parameters)
05 - 08 19: 41: 10.955 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at android.hardware.Camera.native_getParameters(Native Method)
05 - 08 19: 41: 10.955 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at android.hardware.Camera.getParameters(Camera.java: 2075)
05 - 08 19: 41: 10.955 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at ali.simpleflaslight.MainActivity.turnOffFlash(MainActivity.java: 114)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at ali.simpleflaslight.MainActivity.access$100(MainActivity.java: 15)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at ali.simpleflaslight.MainActivity$2.onClick(MainActivity.java: 56)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at android.view.View.performClick(View.java: 4764)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at android.view.View$PerformClick.run(View.java: 19833)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at android.os.Handler.handleCallback(Handler.java: 739)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at android.os.Handler.dispatchMessage(Handler.java: 95)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at android.os.Looper.loop(Looper.java: 135)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at android.app.ActivityThread.main(ActivityThread.java: 5292)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at java.lang.reflect.Method.invoke(Method.java: 372)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java: 908)
05 - 08 19: 41: 10.956 4378 - 4378 / ali.simpleflaslight W / System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 703)

4

1 回答 1

0

首先,你有try / catchcatch(Exception e)绝对不做任何事情 -永远不要这样做 - 这可能是为异常编程的最糟糕的方法之一。至少添加e.printStackTrace()catch块中,然后监视 logcat 的异常 - 我很确定你会发现一些被记录的。

其次,一次只有一个应用程序可以使用相机。最佳做法是release()将相机输入onPause()方法,然后open()将其重新输入onResume()。由于您希望手电筒保持打开状态,因此您可能认为不release()使用相机可以接受 - 内置相机几乎肯定会遵循最佳做法,当它调用时您的手电筒会熄灭,open()然后它会release()离开相机在“重置”阶段。

尝试getCamera()从您的onCreate(...)方法中删除对的调用并将其放入onResume()(在调用turnOnFlash().

于 2015-05-08T23:18:10.823 回答