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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With