Zxing Barcode Scanner 在开始和结束时触发 OnSleep() - OnResume() 方法

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

我正在开发 Xamarin.Forms 应用程序。我有一个触发扫描仪的按钮。

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

我的扫描功能是:

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.", "ΟΚ");
                });
            }
        }
    }

问题是扫描仪真正打开后,触发了App.xaml.cs中的OnSleep()方法

protected override void OnSleep()
{
        
}

protected override void OnResume()
{
        
}

并且在扫描仪关闭后触发 OnResume() 方法。

这种行为是预期的吗?我在扫描仪初始化方面做错了什么吗?

根据评论,您的问题不是抑制您所看到的行为,而是处理它。所以你可以在应用程序中放置一个静态标志 class 这样你就知道扫描器处于活动状态并将你的处理程序代码放入其中。

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;
}

扫描功能:

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;
    }
}