恢复CameraActivity导致java.lang.RuntimeException:无法连接到摄像头服务

时间:2015-10-22 22:10:40

标签: android android-camera surfaceview android-mediarecorder

我有一项使用SurfaceView和MediaRecorder录制视频的活动。每当我暂停去另一个活动时,返回时我会得到以下错误/异常:

CODE

@Override
public void surfaceCreated(SurfaceHolder holder) {
    Log.v(TAG, "surfaceCreated");

    camera = Camera.open();//exception line

    try {
        camera.setPreviewDisplay(holder);
        camera.startPreview();
        previewRunning = true;
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        e.printStackTrace();
    }

}

例外:

java.lang.RuntimeException: Fail to connect to camera service
     at android.hardware.Camera.<init>(Camera.java:545)
     at android.hardware.Camera.open(Camera.java:403)
     at com.mycompany.app.android.CameraActivity.surfaceCreated(CameraActivity.java:362)
     at android.view.SurfaceView.updateWindow(SurfaceView.java:606)
     at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:246)
     at android.view.View.dispatchWindowVisibilityChanged(View.java:9365)
     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1289)
     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1289)
     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1289)
     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1289)
     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1289)
     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1289)
     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1462)
     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1185)
     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6591)
     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
     at android.view.Choreographer.doCallbacks(Choreographer.java:590)
     at android.view.Choreographer.doFrame(Choreographer.java:560)
     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:145)
     at android.app.ActivityThread.main(ActivityThread.java:5837)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
15231-15238/com.mycompany.app.android W/art: Suspending all threads took: 10.396ms

如何防止抛出此异常?

1 个答案:

答案 0 :(得分:0)

试试这个

if(null==camera)
  camera = Camera.open();