I have a Xamarin.Forms app that uses push notifications. For Android, the following line:
(App.Current.MainPage as MainPage)?.AddMessage(body);
that is called from Android native OnMessageReceived(), throws NullReferenceException.
Why can this happen? Isn't App.Current to be accessible from the platform-specific project?
Here is the full OnMessageReceived() code:
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
string messageBody;
if (message.GetNotification() != null)
{
messageBody = message.GetNotification().Body;
}
// NOTE: test messages sent via the Azure portal will be received here
else
{
messageBody = message.Data.Values.First();
}
// convert the incoming message to a local notification
SendLocalNotification(messageBody);
// send the incoming message directly to the MainPage
SendMessageToMainPage(messageBody); // THIS IS THE METHOD WHERE THE PROBLEMATIC LINE IS
}
I also tried to use MessagingCenter instead, like this:
public override void OnMessageReceived(RemoteMessage message)
{
base.OnMessageReceived(message);
string messageBody;
if (message.GetNotification() != null)
{
messageBody = message.GetNotification().Body;
}
// NOTE: test messages sent via the Azure portal will be received here
else
{
messageBody = message.Data.Values.First();
}
// convert the incoming message to a local notification
SendLocalNotification(messageBody);
// send the incoming message directly to the MainPage
MessagingCenter.Send<object>(this, "newCall");
// SendMessageToMainPage(messageBody);
}
But this message is never caught in the shared project's MainPage.xaml.cs.
Same issue with iOS, where I tried to send message from AppDelegate's DidReceiveRemoteNotification()...
Please help.
Yes, I did set the MainPage as App.Current.MainPage. I just following an example that uses that page, but yes, I could use App.cs. I will try it. thanks.
Like you suggested, I placed my handle logic into the App class, and then it worked. Thanks. If you make it an Answer, I will mark it as such.
ok, I will post it as answer .
Sign in to comment