Communication between Xamarin PCL project and Xamarin Android (iOS) project in Xamarin Forms Application

A lot of people ask how is it possible to pass data from Xamarin Android (or iOS) to Xamarin PCL project in a Xamarin Forms Application.

I had the same problem in the past, when I tried to write an application that had a Barcode Reader connected via Bluetooth (you can find something here…) to an Android device. In this App, I receive data form a Bluetooth socket and I need to visualize these data into a Label, but Label is an object present in a Xamarin Forms App, not in the Xamarin Android project.

After some research, I have found two possibility to send data from Xamarin Platform Specific Project to Xamarin PCL projects:

From the documentation…

DependencyService

DependencyService allows apps to call into platform-specific functionality from shared code. This functionality enables Xamarin.Forms apps to do anything that a native app can do.

DependencyService is a dependency resolver. In practice, an interface is defined and DependencyService finds the correct implementation of that interface from the various platform projects.

This solution is useful when you have to execute some code in Xamarin Android project (I am talking about Xamarin Android, but it can be every Platform specific project) in a specific moment. For exemple, when you press a Button on a Xamarin Forms Page, you can retrive device manufacturer: this information can be found with this java property and with this c# code.

First thing to create is the Interface

Interface

 namespace MyApp.Interfaces
 {
     public interface IDevice
     {
         bool IsZebraDevice();
     }
 }

The interface you design will define how you interact with platform-specific functionality

Platform specific code

 [assembly: Xamarin.Forms.Dependency(typeof(Device_Android))]
 namespace Wuerth.Droid
 {
     public class Device_Android : IDevice
     {
         public Device_Android()
         {
         }
 
         public bool IsZebraDevice()
         {
             return Android.OS.Build.Manufacturer == "Zebra Technologies";
         }
     }
 }

In this example I implement on Xamarin Android Project the Interface I have defined in PCL project. IsZebraDevice call an Android code.

The code “[assembly: Xamarin.Forms.Dependency(typeof(Device_Android))]” is the “interface’s registration”.

Use the code

Now you can call the “Native code” from your PCL project

var isZebraDevice = DependencyService.Get<IDevice>().IsZebraDevice();

MessagingCenter

Xamarin.Forms MessagingCenter enables view models and other components to communicate without having to know anything about each other besides a simple Message contract.

This solution is useful when you have to receive from Xamarin Platform Specific Project some data, but you don’t know when these data are ready so you can’t use a Dependency Service. Obviously you can use MessagingCenter to communicate between Xamarin PCL’s object, for example to send data between two Pages.

For example, in my Android Project I have an event that is raised every time a barcode is read.

var my_application = new App();
 
_broadcastReceiver.scanDataReceived += (s, scanData) =>
{
 
        string data = scanData.Replace('\n', ' ').TrimEnd();
        MessagingCenter.Send<App, string>(my_application, "ScanBarcode", data);
};

Whit this code, when “scanDataReceived” receive some data, the “MessagingCenter” Send this data to the Application. I have only to “receive” the data when I need it.

OnAppearingCommand = new Command((obj) => { 
        MessagingCenter.Subscribe<App, string>(this, "ScanBarcode", (arg1, barcode) => {
        ReadBarcode(barcode);
       });
 });

The  Page’s “OnAppearing” event is a good moment to subscribe a MessagingCenter. Received the barcode, I can do what I want with it.

Remember to unsubscribe the MessagingCenter (OnDisappearing is a good moment…)

OnDisappearingCommand = new Command((obj) => {
        MessagingCenter.Unsubscribe<App, string>(this, "ScanBarcode"); 
});

This example works with barcode readers, but it is useful for every situation you receive some data in Platform Specific Project and you have to send it to PCL project (Geolocalization, Beacons, RfID, NFC tags…)

Comments are accepted!

 

5 pensieri su “Communication between Xamarin PCL project and Xamarin Android (iOS) project in Xamarin Forms Application

  1. hi what about when we need a return value in android for example:

    Android:
    OnBackButtonPressed(){
    if (MessagingCenter.Send(my_application, “ScanBarcode”, data)){ // messagecenter not has option to return a bool only void what would be the alternative?
    return;
    }
    }

    "Mi piace"

      • Hi, what I want to do is notify when the android hardware button is pressed to my pcl project but that notification must wait from a response from the pcl project.
        I currently resolve this with a .net standard library class.

        this is the use case :

        user press hardware backbutton .
        in the android poroject inside the method OnBackPressed we communicate the pcl project the event
        the pcl project evaluate if the action should be ignore or not , in case the action should be ignore pcl project return a false value to the android project
        then in the android project in the OnBackPressed we should ignore this base.OnBackPressed();

        something like this:

        Android project hardware button pressed:
        public override void OnBackPressed()
        {

        if (here we send a message or notification to the pcl project to evaluate the action)[ // if false
        return;
        }
        base.OnBackPressed();
        }

        "Mi piace"

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo di WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione /  Modifica )

Google photo

Stai commentando usando il tuo account Google. Chiudi sessione /  Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione /  Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione /  Modifica )

Connessione a %s...