I'm developing a mobile application with Xamarin Forms and Prism for MVVM structure. I have a TC51 Zebra device and I need to intercept the barcode scan event. The SDK is correctly installed in the project but the online example is for Xamarin.Android, not for Xamarin.Forms. I don't know how to send the scanned barcode from Android project to portable project class.
Now I have this "Send call" in MainActivity.cs (Android project):
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);
}
}
}
And this code in my ViewModel (Portable project) constructor:
Xamarin.Forms.MessagingCenter.Subscribe<Xamarin.Forms.Application, string>(Xamarin.Forms.Application.Current, "Barcode", (sender, arg) => { _pageDialogService.DisplayAlertAsync("Test Scan", "Data Received: " + arg, "OK"); });
When I try to read a barcode in this page the app crash.
I have also another problem: Now that I included the SDK in the project the app doesn't work in other devices, it crash on startup. I need to have a single application with barcode scanner support for TC51 Zebra devices and camera barcode scanning for other devices without integrated barcode scanner hardware. Is it possible?
I think you can do something like this.
In your 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);
}
}
}
then, in your "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");
}