Here's some sample code that shows how to display a pop-up alert in Xamarin.Forms when you receive a Push Notification on either platform.
Xamarin.Forms Shared Code
Create a static class
in the Xamarin.Forms shared code that triggers DisplayAlert
. Then create a static
method called ShowAlert
that can be accessed from our platform-specific projects.
public static class PushNotificationHelpers
{
public static async Task ShowAlert(string alert)
{
await Application.Current?.MainPage?.DisplayAlert("Push Notification Received", alert, "OK");
}
}
iOS AppDelegate
To handle the Push Notification on iOS, you will override the ReceivedRemoteNotification
method in the AppDelegate
. The ReceivedRemoteNotification
method is triggered every time the iOS app receives a push notification.
[Register("AppDelegate")]
public partial class AppDelegate : FormsApplicationDelegate
{
.
.
.
public override async void ReceivedRemoteNotification(UIApplication app, NSDictionary userInfo)
{
// Process a notification received while the app was already open
await ProcessNotification(userInfo);
}
async Task ProcessNotification(NSDictionary userInfo)
{
if (userInfo == null)
return;
Console.WriteLine("Received Notification");
var apsKey = new NSString("aps");
if (userInfo.ContainsKey(apsKey))
{
var alertKey = new NSString("alert");
var aps = (NSDictionary)userInfo.ObjectForKey(apsKey);
if (aps.ContainsKey(alertKey))
{
var alert = (NSString)aps.ObjectForKey(alertKey);
await PushNotificationHelpers.ShowAlert(alert.ToString());
Console.WriteLine("Notification: " + alert);
}
}
}
}
Android GcmServiceBase
To handle push notifications on Android, you will create a class that implements GcmServiceBase
and overrides OnMessage
. The OnMessage
method is triggered every time the Android App receives a notification.
[Service(Name="com.sample.evolve.GcmService")] //Must use the service tag
public class GcmService : GcmServiceBase
{
.
.
.
protected override void OnMessage (Context context, Intent intent)
{
Console.WriteLine ("Received Notification");
try
{
//Push Notification arrived - print out the keys/values
if (intent != null || intent.Extras != null)
{
var keyset = intent.Extras.KeySet ();
foreach (var key in keyset)
{
var message = intent.Extras.GetString(key);
Console.WriteLine("Key: {0}, Value: {1}", key, message);
if(key == "message")
await PushNotificationHelpers.ShowAlert(message);
}
}
}
catch(Exception ex)
{
Console.WriteLine ("Error parsing message: " + ex);
}
}
}
Sample App
The Xamarin Evolve app shows how to implement Push Notifications for a Xamarin.Forms app. I highly recommend perusing the Xamarin Evolve app source code to get a better understanding of the above sample code!