CameraView (SurfaceView) preview is black after hiding the fragment

512 views Asked by At

I'm using CameraView, which uses SurfaceView on the API I'm currently testing for, in a fragment to allow the user to take photos with a live preview in my app.

Then, when the photo is taken (and saved to a file), the fragment is hidden, and a second fragment show the picture in a ImageView so the user can check if it was taken correctly.

If I press the phone's back button on this second fragment, the first fragment reappear, but the camera live preview is all black.

I think this has to do with the .start() and .stop() methods that have to be called on the CameraView on onPause() and onResume(), which aren't called when the fragment reappear.

To make up for it, I tried adding the following :

getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        mCameraView.stop();
    }
 });

In my BackgroundHandler before switching to fragment 2, and adding

@Override
public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    if (!hidden) {
        mCameraView.start();
    }
}

In my first fragment, so that the CameraView start again when it reappears... but this doesn't work.

I added breakpoints to check if the lines were running. mCameraView.stop() runs at the right time, but mCameraView.start() seems to run while the second fragment is still visible. Is the problem that onHiddenChanged is being called too early, before the fragment is actually visible, causing the bug?

If that is the case, is there any other function I can Override that runs after a fragment become visible again?

If that's not the problem, do you have any other idea what could be causing the black preview?

Thanks

Here's the code where I switch from the first fragment to the second (no code for the opposite since I just press the back button) :

                    FragmentTransaction ft = getFragmentManager().beginTransaction();
                    photo_fragment2 pf2 = new photo_fragment2();
                    ft.addToBackStack("photo2");
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mCameraView.stop();
                        }
                    });
                    ft.hide(photo_fragment1.this);
                    ft.add(android.R.id.content, pf2);
                    ft.commit();
0

There are 0 answers