Push

The content in this guide refers to the newly released version 3 of the library. You can still access the version 1.x guides here.

Version 1.x is now deprecated. We will continue to support 1.x through March 31, 2017 (End of Support - EOS). If you are currently using 1.x in your apps, you will need to upgrade your apps to 3.x before the EOS date. We have created a migration guide to help you.

Push helps you reach out to your users in a timely fashion with important messages. You can use it to inform users about updates to some piece of data, about new services available nearby or that they are winners in a game. Using Custom server code you can set up triggers which send push notifications to a targeted set of people based on changes in the data you specify.

Kinvey brings Android Push Notifications to you through an integration with Google Cloud Messaging (GCM), and iOS Push Notifications through an integration with AWS SNS. While push notifications can only be configured to be used by either iOS or Android devices, our APIs provide support for registering/unregistering devices and associating them with Kinvey users.

Android

GCM Setup

Navigate to the Google Mobile Services Add Service Wizard and follow the the instructions for creating a project, entering in your app info and adding Google Cloud Messaging to your app. Write down the API Key and Sender ID.

Console Setup

  • On Kinvey's console Navigate to Engagement and select Push.
  • Select Configuration from the top.
  • In the Android section, enter the API Key and Sender ID (also known as Project Number ) obtained in the GCM setup. Push Configuration
  • Click Save Android to save your configuration.

Project Setup

Android Push functionality is provided through a distribution of the Kinvey Library on nuget. If you haven't already installed the Kinvey-Android package, you should install it with the following Nuget command:

nuget Install-Package Kinvey-Android

On your Xamarin Android project, right click Components directory -> Get More Components. In the window that pops up, search for Google Play Services, and install the latest version (>= v22.0.0.0).

Right click your project name -> Options -> on the Build/General tab ensure the Target Framework is set to at least Android 5.0 (Lollipop)

Set your Project ID when you create your client (or modify your existing client):

Client kinveyClient = new Client.Builder(myAppKey, myAppSecret)
            .SetProjectId(myProjectID)
            .build();

Receiving push messages

For push to work, an Android application must implement two classes to receive and handle push notifications.

First, create a new class that extends KinveyGCMService. This class provides 5 methods, one for each of the possible GCM actions. Overriding these methods allows you to run any code when a message is received (for example, showing a notification or just writing to the logs).

using KinveyXamarinAndroid;
...

[Service]
public class GCMService : KinveyGCMService
{
    public override void onMessage(String message)
    {
      displayNotification(message);
    }

    public override void onError(String error)
    {
      displayNotification(error);
    }

    public override void onDelete(int deleted)
    {
      displayNotification(deleted.ToString());
    }

    public override void onRegistered(String gcmID)
    {
      displayNotification(gcmID);
    }

    public override void onUnregistered(String oldID)
    {
      displayNotification(oldID);
    }

    private void displayNotification(String message)
    {
      Console.WriteLine(message);

      NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
        .SetContentTitle("Push Received!") // Set the title
        .SetSmallIcon(Resource.Drawable.Icon) // This is the icon to display
        .SetContentText(message); // the message to display.

      NotificationManager notificationManager = (NotificationManager)GetSystemService(NotificationService);
      notificationManager.Notify(100, builder.Build());
    }
}

Now that you have a class to handle receiving messages, you need to be register it with GCM. Create a new class in the same package as the above, and extend the Android class BroadcastReceiver. This class contains IntentFilters, which will register this BroadcastReceiver to listen for specific intents.

[BroadcastReceiver(Permission= "com.google.android.c2dm.permission.SEND")]
[IntentFilter(new string[] {"com.google.android.c2dm.intent.RECEIVE"})]
[IntentFilter(new string[] {"com.google.android.c2dm.intent.REGISTRATION"})]
[IntentFilter(new string[] {"com.google.android.gcm.intent.RETRY"})]
[IntentFilter(new string[] {"com.kinvey.xamarin.android.ERROR"})]
public class MyGCMBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        Intent i = new Intent(context, typeof(GCMService));
        i.SetAction(intent.Action);
        i.PutExtras (intent.Extras);
        context.StartService(i);

        SetResult(Result.Ok, null, null);
    }
}

In the above code sample, replace GCMService with the name of the KinveyGCMService you created earlier.

Manifest changes

To use GCM for push notifications, add the following permissions to your project's AndroidManifest.xml file within the <manifest> tags:

<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="21"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

Also add the following lines within the <manifest> tags, however replacing com.myPackage with your app's package name.

<permission android:name="com.myPackage.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.myPackage.permission.C2D_MESSAGE" />

Registering the Device

Now that you have configured your manifest and added the two necessary classes, it is necessary to register a device to receive Push notifications. To register the active user to receive push notifications on the current device, use the following:

kinveyClient.Push().Initialize(Android.App.Application.Context);

After registration has completed, your application will be notified via the onRegistered() method of the KinveyGCMService.

Push registration occurs in the context of an initialized Kinvey client and a logged-in Kinvey user (either explicit or implicit).

Disabling Push Notifications

Similarly, the following code will disable push notifications for the current active user and your app will receive results through the KinveyGCMService.

kinveyClient.Push().DisablePush();

iOS

APN and Certificate setup

Navigate to the Xamarin Push Notifications in iOS guide and follow the instructions for Creating and Using Certificates.

To confirm that the configuration is done properly, right click on your project -> Options -> iOS Bundle Signing. Both Signing Identity and Provisioning Profile should be set appropriately for your application.

Console Set Up

  • On Kinvey's console Navigate to Engagement and select Push.
  • Select Configuration from the top.
  • Generate an apple push certificate .p12 file for your app (Instructions).
  • Drag the .p12 file to the iOS configuration on the console.
  • Save your configuration. If this is successful, you will have a Credentials section with the push keys to use in the app.
  • When you are ready to deploy your app, you will have to create an App Store or Ad hoc push certificate and upload that to our service, and then press Deploy to Production.

Project Setup

iOS Push functionality is provided through a distribution of the Kinvey Library on nuget. If you haven't already installed the Kinvey-iOS package, you should install it with the following Nuget command:

nuget Install-Package Kinvey-iOS

Within the FinishedLaunching(UIApplication application) method of your AppDelegate, call:

kinveyClient.Push().RegisterForToken();

Add the following code to your AppDelegate, which will kick off registration with Kinvey and also handle registration errors from iOS. Note this code first checks if a Kinvey User has successfully logged in, and will only attempt to register if they have.

public string myDeviceToken { get; set; }

public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
    myDeviceToken = deviceToken.ToString();

    if (kinveyClient.User().isUserLoggedIn())
    {
      kinveyClient.Push().Initialize(myDeviceToken);
    }
}

public override void FailedToRegisterForRemoteNotifications(UIApplication application , NSError error)
{
    new UIAlertView("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show();
}

Add the following code after successfully logging in a user (the below code assumes this is done in a ViewController). This covers the condition where login finishes before the iOS callback for registration has completed:

string token = ((AppDelegate)UIApplication.SharedApplication.Delegate).myDeviceToken;

if (token != null)
{
  kinveyClient.Push().Initialize(token);
}

Disabling Push Notifications

Similarily, the following code will disable push notifications for the current active user.

kinveyClient.Push().DisablePush();
Got a question?