java – Camera preview freezes after screen lock-ThrowExceptions

Exception or error:

The custom camera app I’ve written stops giving the preview after the screen locks (by pushing lock butten or waiting for a couple of minutes). I don’t get an exception, which makes it quite difficult to find the problem.

Does the android screen lock (if that’s the correct term) pauses/halts/… my App (activity)?

If this were the case, could the cause be my onPause/onResume methods? Or is another cause mor likely?

Thanks in advance

How to solve:

I faced same problem and fixed it using following steps:

  1. I created my camera preview and added it to the container FrameLayout in onResume() of the parent activity. Something like:

    public void onResume{
        super.onResume();
        mCamera = Camera.open();
        if(null != mCamera){
            mCamera.setDisplayOrientation(90);
            mPreview = new CameraOverlay(getActivity(), mCamera);
            frLyParent.addView(mPreview);
        }
    }
    
  2. I removed the view in onPause(). This fixes the freeze.

    public void onPause(){
        super.onPause();
        if(null != mCamera){
            mCamera.release();
            mCamera = null;
        }
        frLyParent.removeView(mPreview);
        mPreview = null;
    }
    

where CameraOverlay() is the class which extends SurfaceView and implements SurfaceHolder.Callback. Do let me know if you need that implementation.

###

here is mine, it does work 🙂

@Override
    public void onResume() {
        super.onResume();
        try {
            camera = Camera.open();
            holder.addCallback(this);
            surface.setVisibility(View.VISIBLE);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onPause() {
        try {
            surface.setVisibility(View.GONE);
            holder.removeCallback(this);
            camera.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onPause();
    }

###

Thanks, I used a modification of this and it works for me too

I added mPreview.removeView(mPreview.mSurfaceView); in onpause(), and mPreview.addView(mPreview.mSurfaceView); in onResume() before opening the camera.

I also deleted addView(mSurfaceView); in the preview class.

###

In onResume() method add this line :

surfaceView.setVisibility(View.VISIBLE);

In onPaused() method add this line :

surfaceView.setVisibility(View.GONE);

Leave a Reply

Your email address will not be published. Required fields are marked *