Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin - is there a way to notify Xamarin.Forms from a native project?

So, I have this code in my native project (Android MainActivity OnCreate), which doesn't do anything:

var container = TinyIoCContainer.Current;
TinyMessengerHub tmh = (TinyMessengerHub)container.Resolve<ITinyMessengerHub>();

tmh.Subscribe<LocalMessage>((m) => {
    // this doesn't show
    Toast.MakeText(this, m.Content, ToastLength.Long);
});

Here's where I notify the app using TinyMessenger:

[Service(Exported = false), IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" })]
class MyGcmListenerService : GcmListenerService
{
    public override void OnMessageReceived(string from, Bundle data)
    {
        string msg = data.GetString("message");

        var container = TinyIoCContainer.Current;
        TinyMessengerHub tmh = (TinyMessengerHub)container.Resolve<ITinyMessengerHub>();
        tmh.Publish(new LocalMessage(this, msg));
    }
}

I tried to add TinyMessenger to my PCL, but apparently it was not supported (there were missing references in the TinyIoc.cs file etc., the same code runs well in the Android project)

So, is there any way to inform Xamarin.Forms about an arriving message so that I could e.g. display an alert window?

like image 786
mkkekkonen Avatar asked Mar 12 '23 02:03

mkkekkonen


1 Answers

This example is done with a Page, but you can subscribe/unsubscribe with your Application class, or selectively within your app logic.

In your Xamarin.Forms project subscribe/unsubscribe to a message via MessageCenter:

protected override void OnAppearing()
{
    base.OnAppearing();
    MessagingCenter.Subscribe<object, string>(this, "ShowAlertMessage", (sender, msg) =>
    {
        Device.BeginInvokeOnMainThread(() => {
            MainPage.DisplayAlert("Push message", msg, "OK"); 
        });
    });
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    MessagingCenter.Unsubscribe<object>(this, "ShowAlertMessage");
}

In "native" project send message via MessageCenter:

MessagingCenter.Send<object, string> (this, "ShowAlertMessage", "StackOverFlow Rocks");
like image 87
SushiHangover Avatar answered Mar 21 '23 17:03

SushiHangover