方法释放异常相机预览之后调用(Method called after release Excepti

2019-07-03 13:49发布

我有在使用我的CameraPreview类中的一个活动类(CameraActivity)。 在“的onResume”相机和预览发起。 在“在onPause”,我释放相机资源。 当应用程序被启动,一切工作正常里面的“的onResume”但是当我(在浏览器如打开URL)开始通过意向另一个活动,然后回到我的活动,则异常“的onResume”发起CamerPreview类中发生。 请找到下面的代码:

// CameraActivity类

public void onResume(){
    super.onResume();
    Log.d("inside onResume, camera==="+mCamera, "inside onResume");
    try {
        if(mCamera==null)
        {

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);


        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();
        int rotation = this.getWindowManager().getDefaultDisplay().getRotation();


        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);

        FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);



    }





} catch (Exception e) {
    // TODO Auto-generated catch block
    Log.e("onResume",Log.getStackTraceString(e));
}



public void onPause{
    try {
        super.onPause();
        if (mCamera != null) {
            previewing = false;
            mCamera.stopPreview();
                mCamera.setPreviewCallback(null);
                mCamera.release();
                mCamera = null;
                mPreview=null;


    }
} catch (Exception e) {
    // TODO Auto-generated catch block
    Log.e("releaseCamera",Log.getStackTraceString(e));
}
}



 public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
            Log.e("getCameraInstance",Log.getStackTraceString(e));

    }
    return c;
}

//以下是CameraPreview类:

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private SurfaceHolder mHolder;
    Camera mCamera;
    PreviewCallback previewCallback;
    AutoFocusCallback autoFocusCallback;
    private int rotation;
    public int getRotation() {
        return rotation;
    }

    public void setRotation(int rotation) {
        this.rotation = rotation;
    }

    public CameraPreview(Context context, Camera camera,
                         PreviewCallback previewCb,
                         AutoFocusCallback autoFocusCb) {
        super(context);
        mCamera = camera;
        previewCallback = previewCb;
        autoFocusCallback = autoFocusCb;

        /*
         * Set camera to continuous focus if supported, otherwise use
         * software auto-focus. Only works for API level >=9.
         */
        /*
        Camera.Parameters parameters = camera.getParameters();
        for (String f : parameters.getSupportedFocusModes()) {
            if (f == Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) {
                mCamera.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                autoFocusCallback = null;
                break;
            }
        }
        */

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }


    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            if(mCamera==null){
                mCamera=Camera.open();
            }
            mCamera.setPreviewDisplay(holder);
        } catch (IOException e) {
            Log.d("DBG", "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {

        // Camera preview released in activity
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        /*
         * If your preview can change or rotate, take care of those events here.
         * Make sure to stop the preview before resizing or reformatting it.
         */
        if (mHolder.getSurface() == null){
          // preview surface does not exist
          return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e){
          // ignore: tried to stop a non-existent preview
        }

try{
            mCamera.setPreviewDisplay(mHolder);
            mCamera.setPreviewCallback(previewCallback);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
        } catch (Exception e){
            Log.d("DBG", "Error starting camera preview: " + e.getMessage());
        }
    }

}

这是logcat的:

11-05 10:14:34.585: E/AndroidRuntime(7864): FATAL EXCEPTION: main
11-05 10:14:34.585: E/AndroidRuntime(7864): java.lang.RuntimeException: Method called after release()
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.hardware.Camera.setPreviewDisplay(Native Method)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.hardware.Camera.setPreviewDisplay(Camera.java:393)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.intagleo.qraugmented.detection.camera.CameraPreview.surfaceCreated(CameraPreview.java:74)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.SurfaceView.updateWindow(SurfaceView.java:552)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:215)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewRoot.performTraversals(ViewRoot.java:790)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.os.Looper.loop(Looper.java:130)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at android.app.ActivityThread.main(ActivityThread.java:3687)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at java.lang.reflect.Method.invokeNative(Native Method)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at java.lang.reflect.Method.invoke(Method.java:507)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-05 10:14:34.585: E/AndroidRuntime(7864):     at dalvik.system.NativeStart.main(Native Method)

编辑

我更新了“surfaceDestroyed”,并把记录作为建议,但现在我在“的onPause”越来越例外 - > onSurfaceDestroyed。 最初的onPause是执行罚款。

1-相机实例在活动类的“的onResume”通过方法“getCameraInstance”创建并传递mCamera实例CameraPreview类。 我试图改变它,以便创建该相机实例只能有越位“onSurfaceCreated”并分配回mCamera实例的活动课,但没有奏效。 我还通过调试说,“CameraPreview”类的previewCallBack成员是有效的第一次,但第二次发现“CameraPreview”类的“previewCallBack”成员为空。

注意当“的onResume”被称为是第一次,一切正常,但是当它的onPause之后运行第二次则异常发生最初虽然代码是的onResume相同。

11-06 01:25:28.375: I/onResume(4332): INITIATED
// Workinf fine till now. Now opening another intent activity
11-06 01:26:23.500: I/onPause(4332): INITIATED
11-06 01:26:23.804: "OnSurfaceDestroyed": "Initiated"
11-06 01:26:23.945: E/AndroidRuntime(4332): FATAL EXCEPTION: main
11-06 01:26:23.945: E/AndroidRuntime(4332): java.lang.RuntimeException: Method called after release()
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.hardware.Camera.stopPreview(Native Method)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.intagleo.qraugmented.detection.camera.CameraPreview.surfaceDestroyed(CameraPreview.java:85)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.reportSurfaceDestroyed(SurfaceView.java:596)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.updateWindow(SurfaceView.java:490)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:215)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.View.dispatchWindowVisibilityChanged(View.java:4027)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:720)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewRoot.performTraversals(ViewRoot.java:790)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1867)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.os.Looper.loop(Looper.java:130)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at android.app.ActivityThread.main(ActivityThread.java:3687)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at java.lang.reflect.Method.invokeNative(Native Method)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at java.lang.reflect.Method.invoke(Method.java:507)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-06 01:26:23.945: E/AndroidRuntime(4332):     at dalvik.system.NativeStart.main(Native Method)

Answer 1:

正如你所添加的摄像头到FrameLayout里,像这样的:

FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
preview.addView(mPreview);

surfaceCreated方法将被调用,所以mCamera.setPreviewDisplay(holder); 将被调用。

当您创建/打开一个新的摄像头, FrameLayout还有你以前的相机,因此其surfaceCreated将除了您的新相机被调用。

你应该做的,是删除以前从相机FrameLayout当你释放你的相机(上onPause()方法)是这样的:

preview.removeView(mPreview);

希望能帮助到你。



Answer 2:

Dan is right. Also see here.

code sample:

public class MainActivity extends Activity {
    private FrameLayout mFlCameraPreview;
    private Camera mCamera;
    private CameraPreview mCameraPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mFlCameraPreview = (FrameLayout) findViewById(R.id.main_fl_camera_preview);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mCamera == null) {
            mCamera = getCameraInstance();
        }

        if (mCameraPreview == null) {
            mCameraPreview = new CameraPreview(this, mCamera);
            mFlCameraPreview.addView(mCameraPreview);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }

        if (mCameraPreview != null) {
            mFlCameraPreview.removeView(mCameraPreview);
            mCameraPreview = null;
        }
    }

    public static Camera getCameraInstance() {
        Camera camera = null;
        try {
            camera = Camera.open();
        } catch (Exception e) {

        }
        return camera;
    }
}  


Answer 3:

编辑

这是一个艰难的一个回答,我不能100%确定是什么导致你的异常现在。 我已经包括了我的相机,下面的代码,希望这会帮助,我用startCamera()stopCamera()我在调用方法onPauseonResume 。 我也只创建一个新的实例CameraPreview在我的课onCreate ,我不重新实例onResume除非我cameraView == null 。 有一对夫妇的事情,我们做的是不同的。 希望下面的代码将帮助,也许你可以用它玩得到你的工作:

PS:一切为我工作。 即走进以外的活动,等等。我还没有测试生命周期的唯一部分onDestroy ,但那是因为我的应用程序被设计在这个周期开始启动。

MainActivity:

boolean cameraReleased = false;

@Override
protected void onPause() {
    Log.i("onPause", "CALLED:: cameraReleased = " + cameraReleased);
    Log.i("onResume", "CALLED:: cameraView = " + cameraView.toString());
    if (cameraReleased == false) {
        image = null;
        imageResult.setImageBitmap(null);
        imageResult.setImageResource(0);
        cameraView.stopCamera();
        cameraReleased = true;
    }

    if (cameraView == null) {
        Log.i("onPause", "cameraView == null");
        cameraView = new JJCameraSurfaceView(getApplicationContext());
        imageResult = new ImageView(getApplicationContext());
    }
    super.onPause();
}

@Override
protected void onDestroy() {
    Log.e("onDestroy", "INITIATED");
    super.onDestroy();
}

@Override
protected void onResume() {
    Log.i("onResume", "CALLED:: cameraReleased = " + cameraReleased);
    Log.i("onResume", "CALLED:: cameraView = " + cameraView.toString());
    if (cameraReleased == true) {
        image = null;
        imageResult.setImageBitmap(null);
        imageResult.setImageResource(0);
        cameraView.startCamera();
    }

    if (cameraView == null) {
        Log.i("onResume", "cameraView == null");
        cameraView = new JJCameraPreview(getApplicationContext());
        imageResult = new ImageView(getApplicationContext());
    }

    super.onResume();
}

@Override
public void onBackPressed() {
    // If Statement used to get out of my camera view and back to my MainActivity - Same Class
    if (“Camera Preview or Image Result is displayed”) {
        cameraView.stopCamera();
        image = null;
        imageResult.setImageBitmap(null);
        imageResult.setImageResource(0);
        cameraView.startCamera();
        return;
    }

    Log.i("onBackPressed", "WAS PRESSED");
    super.onBackPressed();
}

CameraPreview:

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    Log.w("surfaceChanged", "STARTED");
    if (camera != null) {
        Log.w("surfaceChanged", "camera = NOT NULL");
        Camera.Parameters cParams = camera.getParameters();
        cParams.setPreviewSize(width, height);
        cParams.setSceneMode(Parameters.SCENE_MODE_NIGHT);
        camera.setParameters(cParams);
        camera.startPreview();
    }
}

public void surfaceCreated(SurfaceHolder holder) {
    Log.w("surfaceCreated", "STARTED");
    if (camera == null) {
        camera = Camera.open(); 
    }
    try {
        camera.setPreviewDisplay(mHolder);
    } catch (Exception e) {
        Log.e("setPreviewDisplay", "FAILED: " + e.getMessage());
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
    Log.w("CameraSurfaceDestroyed", "INITIATED");
    camera.stopPreview();
    camera.release();
    camera = null;
}

public void startCamera() {
    Log.w("startCamera", "CALLED");
    mHolder = getHolder();
    surfaceCreated(mHolder);
    camera.startPreview();
    mHolder.addCallback(this);
}

public void stopCamera() {
    mHolder = getHolder();
    mHolder.removeCallback(this);
    camera.stopPreview();
}


Answer 4:

我也有类似的问题,我的代码,这是强制关闭与Method called after release()错误。

我打电话一个SetupCamera()在方法OnResume()其中检查空camera对象,然后调用camera.Open()

什么固定我的问题是要摆脱空检查并调用camera.Open()它是否是空或不是(我已经设定camera = nullonPause看完后) 相机文档 。

我知道这是在跟踪我的问题不是绝对的,但它绝对是为我工作!



Answer 5:

我工作的解决方案:第一:在CameraActivity类中声明mCamera为数组:

Camera mCamera[] = new Camera[1];

第二:构造函数的声明CameraPreview必须是这样的:

public CameraPreview(Context context, Camera[] camera,
                     PreviewCallback previewCb,
                     AutoFocusCallback autoFocusCb) {
      mCamera = camera;
      ...
}

mCameraCameraPreview类必须声明如下:

Camera[] mCamera; // without instantiating of the array!

最后:在所有的方法都里面的类就应该更换所有引用mCamera通过mCamera[0]

PS:对不起,我的英语



Answer 6:

尝试下面的代码,而不是重写的onPause()和的onResume(),重写的onStop()和onRestart()。 在活动周期,的onStop()当活动是不可见的,下一个生命周期方法调用是将onRestart称为()。 看看下面的代码。

@Override
    protected void onStop() {
        super.onStop();
        try {
            m_camera.stopPreview();
            m_camera.release();
            preview.removeView(m_CameraPreview);
/*
m_CameraPreview is the object of the class that looks like this :                                public class CameraSurfaceView extends SurfaceView implements Callback
*/
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        m_camera=getCameraInstance();//Initialize the camera in your own way
        m_CameraPreview = new CameraSurfaceView(this, m_camera);
       preview = (FrameLayout)findViewById(R.id.camera_preview);   
        preview.addView(this.m_CameraPreview);
/* 
*camera_preview is the id of the framelayout defined in xml file and preview is *the instance of FrameLayout. 
*/
    }

正如丹说,框架布局将保持以前的相机实例及其surfaceview回调将除了创造竞争条件的新对象被创建。 因此,你需要释放它的onStop()和onRestart重新初始化()。 希望这可以帮助。



Answer 7:

我得到同样的错误。 以下顺序解决我的问题。

呼叫getHolder().removeCallback(this);surfaceDestroyed()

呼叫

 private void releaseCameraAndPreview() {

        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }

        if(mPreview != null){
            mPreview.destroyDrawingCache();
            mPreview.mCamera = null;
        }

    }

onPause

呼叫

  private boolean safeCameraOpenInView(View view) {
        boolean qOpened = false;
        releaseCameraAndPreview();
        mCamera = getCameraInstance();
        mCameraView = view;
        qOpened = (mCamera != null);

        if(qOpened == true){
            mPreview = new CameraPreview(getActivity().getBaseContext(), mCamera,view);
            preview = (FrameLayout) view.findViewById(R.id.camera_preview);
            preview.addView(mPreview);
            mPreview.startCameraPreview();
        }
        return qOpened;
    }

onCreateView()



文章来源: Method called after release Exception Camera preview