Zxing条形码扫描仪在开始和结束时触发OnSleep()-OnResume()方法



我正在开发一个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((方法。

这种行为是意料之中的吗?扫描仪初始化是否有问题?

根据评论,你的问题不是抑制你看到的行为,而是处理它。所以你可以在App类中放置一个静态标志,这样你就知道扫描仪是活动的,并将处理程序代码放在里面。

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

相关内容

最新更新