开发者

Runtime Error: failed to connect to camera service in android

I wanted 开发者_如何学JAVAto make use of the zxing library to detect qrcodes in my app. But for the apps viewing purpose, i had to change the custom display orientation to portrait. Hence i had to integrate the whole zxing library into my app and addded camera.setDisplayOrientation(90) to the openDriver() method. After doing this, the program works, but I get "Runtime exceptions : Fail to connect to camera service" randomly.

public void openDriver(SurfaceHolder holder) throws IOException {
  if (camera == null) {
      camera = Camera.open();
      camera.setDisplayOrientation(90);

      if (camera == null) {
          throw new IOException();
      }
  }
  camera.setPreviewDisplay(holder);
  if (!initialized) {
  initialized = true;
  configManager.initFromCameraParameters(camera);
}
configManager.setDesiredCameraParameters(camera);

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
reverseImage = prefs.getBoolean(PreferencesActivity.KEY_REVERSE_IMAGE, false);
if (prefs.getBoolean(PreferencesActivity.KEY_FRONT_LIGHT, false)) {
  FlashlightManager.enableFlashlight();
 }
}

public void closeDriver() {
    if (camera != null) {
        FlashlightManager.disableFlashlight();
        camera.release();
        camera = null;
        framingRect = null;
        framingRectInPreview = null;
    }
}

/**
 * Asks the camera hardware to begin drawing preview frames to the screen.
 */
public void startPreview() {
    if (camera != null && !previewing) {
        camera.startPreview();
        previewing = true;
    }
}

/**
 * Tells the camera to stop drawing preview frames.
 */
public void stopPreview() {
    if (camera != null && previewing) {
        if (!useOneShotPreviewCallback) {
            camera.setPreviewCallback(null);
        }
        camera.stopPreview();
        previewCallback.setHandler(null, 0);
        autoFocusCallback.setHandler(null, 0);
        previewing = false;
    }
}    


I doubt that the orientation change is causing that. I have found you will get that error whenever an activity stops but fails to call Camera.release in their onPause. The result is that the next time you try to do Camera.open you get that runtime error since the driver still considers it open regardless of the app/activity that opened it being gone.

You can easily get this to happen while debugging/testing stuff when something throws an exception and brings the activity down. You need to be very diligent about catching all exceptions and being sure to release the camera before finishing the activity.

BTW, are you finding you need to power cycle the device in order to be able to open the camera again?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜