我正在开发一个带有Xamarin Forms和Prism for MVVM结构的移动应用程序。 我有一个TC51 Zebra设备,我需要拦截条形码扫描事件。 SDK已在项目中正确安装,但在线示例适用于Xamarin.Android,而不适用于Xamarin.Forms。 我不知道如何将扫描的条形码从Android项目发送到便携式项目类。
现在我在MainActivity.cs(Android项目)中有“发送呼叫”:
void scanner_Data(object sender, Scanner.DataEventArgs e)
{
ScanDataCollection scanDataCollection = e.P0;
if ((scanDataCollection != null) && (scanDataCollection.Result == ScannerResults.Success))
{
IList <ScanDataCollection.ScanData> scanData = scanDataCollection.GetScanData();
foreach (ScanDataCollection.ScanData data in scanData)
{
Xamarin.Forms.MessagingCenter.Send<Xamarin.Forms.Application, string>((Xamarin.Forms.Application)Xamarin.Forms.Application.Current, "Barcode", data.Data);
}
}
}
这个代码在我的ViewModel(可移植项目)构造函数中:
Xamarin.Forms.MessagingCenter.Subscribe<Xamarin.Forms.Application, string>(Xamarin.Forms.Application.Current, "Barcode", (sender, arg) => { _pageDialogService.DisplayAlertAsync("Test Scan", "Data Received: " + arg, "OK"); });
当我尝试在此页面中阅读条形码时,应用程序崩溃。
我还有另一个问题:现在我将SDK包含在项目中,该应用程序无法在其他设备中运行,它在启动时崩溃。我需要一个单独的应用程序,支持TC51 Zebra设备的条形码扫描仪,以及没有集成条形码扫描仪硬件的其他设备的相机条形码扫描。有可能吗?
答案 0 :(得分:3)
我认为你可以做这样的事情。
在您的MainActivity.cs
中 private App _my_application;
protected override void OnCreate (Bundle savedInstanceState)
{
// .... various things....
global::Xamarin.Forms.Forms.Init (this, savedInstanceState);
_my_application = new App ();
LoadApplication (my_application);
}
void scanner_Data(object sender, Scanner.DataEventArgs e)
{
ScanDataCollection scanDataCollection = e.P0;
if ((scanDataCollection != null) && (scanDataCollection.Result == ScannerResults.Success))
{
IList <ScanDataCollection.ScanData> scanData = scanDataCollection.GetScanData();
foreach (ScanDataCollection.ScanData data in scanData)
{
MessagingCenter.Send<App, string> (my_application, "ScanBarcode", data.Data);
}
}
}
然后,在你的“ContentPage”
中 protected override void OnAppearing ()
{
base.OnAppearing ();
// Enable receive barcode
MessagingCenter.Subscribe<App, string> (this, "ScanBarcode", (sender, arg) => {
// In "arg" there is your barcode
try
{
Device.BeginInvokeOnMainThread(() =>
{
DisplayAlert("BARCODE READ", arg, "OK");
});
}
catch(Exception ex){
System.Diagnostics.Debug.WriteLine(ex.Message);
}
});
}
protected override void OnDisappearing ()
{
base.OnDisappearing ();
// Disable receive barcode
MessagingCenter.Unsubscribe<App, string> (this, "ScanBarcode");
}