Skip to content

Android: Re-evaluate camera locking logic #375

@opcodewriter

Description

@opcodewriter

I'm using ZXingScannerFragment and I see a problem accessing the camera after navigating away from the Activity which contains the fragment.
I'm calling StopScanning like this

        public override void OnPause ()
        {
            base.OnPause ();
            _scannerFragment.StopScanning ();
        }

I have a settings screen where I enumerate available cameras so that user can select the front or back camera for scanning. Sometimes the camera id list is empty, sometimes it's non-empty but accessing a camera throws CameraException, and sometimes everything works!:

CameraMaanager cameraManager = (CameraManager)topActivity.GetSystemService (Context.CameraService);
string[] cameraIdList = cameraManager.GetCameraIdList ();
return cameraIdList.Select ((iCamera) => GetCameraInfo(iCamera)).ToList ();

Digging in the ZXing.Net.Mobile code, I can see that ZXingSurfaceView.ShutdownCamera() starts a thread which runs different shutdown stuff:

https://github.com/Redth/ZXing.Net.Mobile/blob/master/Source/ZXing.Net.Mobile.Android/ZXingSurfaceView.cs#L506

            // make this asyncronous so that we can return from the view straight away instead of waiting for the camera to release.
            Task.Factory.StartNew (() => {
                try {
                    if (theCamera != null) {
                        try {
                            theCamera.SetPreviewCallback (null);
                            theCamera.SetPreviewDisplay (null);
                            theCamera.StopPreview ();
                        } catch (Exception ex) {
                            Android.Util.Log.Error (MobileBarcodeScanner.TAG, ex.ToString ());
                        }
                        theCamera.Release ();
                    }
                } catch (Exception e) {
                    Android.Util.Log.Error (MobileBarcodeScanner.TAG, e.ToString ());
                } finally {
                    ReleaseExclusiveAccess ();
                }
            });

But this makes it hard for me to know in my code when I can access the camera without errors.
I wish the stopping mechanism was awaitable. Or maybe there is already a way I'm not aware of?
Maybe I'm missing something, but this looks to me like a big problem. Is there a workaround?

I can't see other solution than having a loop which runs until a non-empty camera id list is available and no CameraException are caught....
I'd appreciate some thoughts...

Metadata

Metadata

Assignees

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions