Both trying to display a toast and to start a new activity fail. There HAS to be a way to make this work. Is there a way to notify the UI about something happening, an event or something?
Right now I am only able to log the info about the messages to console output.
The context itself is not null, but something else, possibly related to it, is causing the null reference exception.
Here's my code:
[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");
// this fails
Toast.MakeText(this, msg, ToastLength.Long).Show();
// this fails too
Intent pa = new Intent(this, typeof(PopupActivity));
pa.AddFlags(ActivityFlags.NewTask);
StartActivity(pa);
}
}
This is a context Error. This is null therefore you get a null exception pointer. It is null because it is inside a service and not an activity.
You should try to use Application.Context
instead of this
. It is a static in Xamarin.Droid and should return the context.
(Note that I can't test is atm)
I resolved this issue with Xamarin.Forms and MessagingCenter.
Here's my service:
[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");
// send a string via Xamarin MessagingCenter
MessagingCenter.Send<object, string>(this, "ShowAlert", msg);
}
}
And here's part of my PCL App class constructor:
// subscribe to the messages
MessagingCenter.Subscribe<object, string>(this, "ShowAlert", (s, msg) =>
{
// run on UI thread
Device.BeginInvokeOnMainThread(() =>
{
MainPage.DisplayAlert("Push message", msg, "OK");
});
});