如何开启&在服务中关闭闪光灯相机

时间:2013-05-18 06:01:44

标签: android service camera

我正在使用On& amp;关闭相机的闪光灯,它工作正常,但我的移动相机应用程序崩溃,我无法释放服务中的相机

Camera camera = Camera.open(); 
final Parameters p = camera.getParameters();       
          if (isFlashOn) 
          {
              Log.i("info", "torch is turned off!");

             Toast toast= Toast.makeText(getApplicationContext(),
                        "Torch is turned off!",Toast.LENGTH_SHORT);
             toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 100);
             toast.show();

            p.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(p);        

              //Set flag to false               
             isFlashOn = false;
            release=true;

          }
          //If Flag is set to false
          else 
          {
              Log.i("info", "torch is turned on!");

             Toast toast= Toast.makeText(getApplicationContext(),
                        "Torch is turned on!",Toast.LENGTH_SHORT);
              toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 100);
              toast.show();

              p.setFlashMode(Parameters.FLASH_MODE_TORCH);

             camera.setParameters(p);

            isFlashOn = true;
            release=false;

          }

        if (release == true) 
          {
            camera.stopPreview();
            camera.release();
                  }

1 个答案:

答案 0 :(得分:1)

您必须安全地打开相机,因此在直接打开相机之前必须检查相机状态。

private boolean safeCameraOpen(int id) {
    boolean qOpened = false;

    try {
        releaseCameraAndPreview();
        mCamera = Camera.open(id);
        qOpened = (mCamera != null);
    } catch (Exception e) {
        Log.e(getString(R.string.app_name), "failed to open Camera");
        e.printStackTrace();
    }

    return qOpened;    
}

private void releaseCameraAndPreview() {
    mPreview.setCamera(null);
    if (mCamera != null) {
        mCamera.release();
        mCamera = null;
    }
}

For Further Details about Camera检查并根据您的需要进行调整。

享受!!!