我正在開發一個 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() 方法。
這種行為是預期的嗎?我在掃描儀初始化方面做錯了嗎?
uj5u.com熱心網友回復:
根據評論,您的問題將變成不是壓制您所看到的行為,而是處理它。因此,您可以在 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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/415578.html
標籤:
