Home > Blockchain >  Zxing Barcode Scanner triggers OnSleep() - OnResume() Methods on start and on finish
Zxing Barcode Scanner triggers OnSleep() - OnResume() Methods on start and on finish

Time:01-20

I'm developing a Xamarin.Forms app. I have a button which triggers the Scanner.

<Button VerticalOptions="Center"
        IsVisible="False"
        Text="Scan"
        CornerRadius="10"
        FontSize="Medium"
        FontAttributes="Bold"
        TextColor="White"
        Clicked="Scan"
        x:Name="btnScan"/>

My scanning function is:

private async void Scan(object sender, EventArgs e)
    {
        PermissionStatus granted = await Permissions.CheckStatusAsync<Permissions.Camera>();
        if (granted != PermissionStatus.Granted)
        {
            _ = await Permissions.RequestAsync<Permissions.Camera>();
        }
        if (granted == PermissionStatus.Granted)
        {
            try
            {
                MobileBarcodeScanningOptions optionsCustom = new MobileBarcodeScanningOptions();

                scanner = new MobileBarcodeScanner();
                scanner.TopText = "Insert";
                scanner.BottomText = "Align red line with Barcode";

                optionsCustom.DelayBetweenContinuousScans = 3000;
                scanner.ScanContinuously(optionsCustom, ScanResult);

            }
            catch (Exception)
            {
                scanner.Cancel();
                Device.BeginInvokeOnMainThread(async () =>
                {
                    await DisplayAlert("Problem", "Something went wrong.", "ΟΚ");
                });
            }
        }
    }

The problem is after the scanner is actually opened, the OnSleep() method in App.xaml.cs is triggered.

protected override void OnSleep()
{
        
}

protected override void OnResume()
{
        
}

And after the scanner is closed the OnResume() method is triggered.

Is this behavior expected? Am i doing something wrong with the scanner initialization?

CodePudding user response:

Based on the comments, your question then becomes not to suppress the behaviour you're seeing but handle it. So you could put a static flag in the App class so you know the scanner is active and put your handler code inside this.

App.xaml.cs:

public static bool ScannerActive { get; set; }

protected override void OnSleep()
{
    if (!ScannerActive)
    {
        HandleOnSleep();
    }
}

protected override void OnResume()
{
    if (!ScannerActive)
    {
        HandleOnResume();
    }

    // Reset the flag if we are coming back from the scanner
    else App.ScannerActive = false;
}

Scanning function:

private async void Scan(object sender, EventArgs e)
{
    App.ScannerActive = true;

    try
    {
        // ... //
        scanner.ScanContinuously(optionsCustom, ScanResult);
    }
    catch (Exception)
    {
        // Reset flag if it crashed out
        App.ScannerActive = false;
    }
}
  •  Tags:  
  • Related