Push

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

Console Set Up

  1. Navigate to the Firebase Console and follow the guide to create a new project or select an existing project.
  2. Click the gear icon in the top left of the side menu and select Project Settings.
  3. Click on the Cloud Messaging tab and write down the Server Key and Sender ID.
  4. On Kinvey's console select your App.
  5. Navigate to Engagement and select Push.
  6. Click Configure Push.
  7. In the Android section, enter the Server Key and Sender ID (formely known as Project Number) obtained in step 3.
  8. Click Save

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(Android.App.Application.Context);

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

When using Apple Push Notification service (APNS) you will get two push certificates; one for development and one for production/ad-hoc. These certificates require push notifications to be sent to different servers depending on if your app is in development or production.

The production certificate is only usable if your app is in the App Store.

  1. Generate an Apple Push Certificate .p12 file for your app (instructions).
  2. After you export the .p12 file, on Kinvey's console navigate to Engagement and select Push.
  3. Click Configure Push.
  4. In the iOS section drag your .p12 file generated in step 1 where it says Drag here or click to upload a .p12 file.
  5. Click Save
  6. When you are ready to deploy your app, use your production/ad-hoc certificate. Export the .p12 file, and upload that to our service. Then select production as the certificate type and click Save. Deploying your application is a one-time action and cannot be undone.

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?