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 Firebase Cloud Messaging (FCM) 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.
Setup
Console Setup
- Navigate to the Firebase Console and follow the guide to create a new project or select an existing project.
- Click the gear icon in the top left of the side menu and select Project Settings.
- Click on the Cloud Messaging tab and write down the
Sender ID
andServer Key
(formerly known asProject Number
). - On Kinvey's console select your App.
- Navigate to Engagement and select Push.
- Click Configure Push.
- In the Android section, fill in the Sender ID and Server Key fields with the respective
Sender ID
andServer Key
values obtained in step 3. - Click Save
Project Setup
If you don't have the Kinvey Android Client Library added to your project, first take a look at the getting started guide.
Next, obtain the Firebase Messaging Library by adding com.google.firebase:firebase-messaging:17.3.4
to your Gradle file. If you are not using Gradle, import this as a project into your IDE as an Android Library project and add it as a dependency to your application.
kinvey.properties
To use push features, you must use a property file for initializing the client. Take a look at the getting started guide's section on initializing from a property file first, and then you can add the following FCM specific properties:
# Required settings
fcm.enabled=true
fcm.senderID=mySenderID
To use FCM, fcm.enabled
must be set to true. Replace mySenderID
with your Sender Id (a.k.a. Project Number) obtained from your Firebase Project.
Receiving push messages
You must implement a class inheriting from KinveyFCMService
in order to receive and handle push notifications within your Android application. An example is given below, which displays a notification for a push message received.
import com.kinvey.android.push.KinveyFCMService;
public class FCMService extends KinveyFCMService {
@Override
public void onMessage(String message) {
displayNotification(message);
}
private void displayNotification(String message){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getApplicationContext()
.getResources()
.getString(R.string.app_name))
.setContentText(message);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
After defining the class which will handle push messages, you have to register this class with FCM. This will be done in the Android Manifest file, and is described below.
Manifest changes
To use FCM for push notifications, add the following permission to your project AndroidManifest.xml file within the <manifest>
tags:
<uses-permission android:name="android.permission.INTERNET" />
Also, add the following within your <application>
tag to register your FCM service:
<service android:name=".FCMService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Registering the Device
Now that you have configured FCM, 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:
myClient.push(FCMService.class).initialize(getApplication());
Triggering Push Notifications
In addition to using the Console, you can trigger a push notification from Business Logic or a Flex service. This approach allows for greater flexibility as it makes it possible to schedule push notifications, to tie them down to various data events, and to set advanced options supported by Android and iOS.
You can send push notification from either collection hooks, effectively tying the notification to a data event, or custom endpoints which you can call manually or programmatically when needed.
The methods for sending push notifications are provided by the push
module available in both Business Logic and the Flex SDK. They include send()
, sendMessage()
, sendPayload()
, broadcastPayload()
, and broadcastMessage()
. Check the module's reference for detailed information.
The following code uses the onPreSave()
before-processing collection hook to send a simple push notification to all users who fancy the winning team. Instead of saving any data to the data store, this request just causes the push notification to be sent.
function onPreSave(request,response,modules){
var userCollection = modules.collectionAccess.collection('user')
, utils = modules.utils
, push = modules.push
, template = '{{name}}, the {{team}} just won!'
, pushedMessageCount = 0
, userCount;
// Find all users whose favoriteTeam matches
// the incoming request's winning team.
userCollection.findAsync({"favoriteTeam": request.body.winningTeam})
.then(function(userDocs){
// Total number of messages to send
userCount = userDocs.length;
// Each message is customized
userDocs.forEach(function(doc){
var values = {
name: doc.givenName,
team: doc.favoriteTeam
};
// Render the message to send
var message = utils.renderTemplate(template, values);
// Send the push
push.send(doc, message);
// Keep track of how many pushes are sent
pushedMessageCount++;
// Reduce the number of users left to push to
userCount--;
if (userCount <= 0){
// All pushes sent out, complete the request
response.body = {
"message": "Attempted to push "
+ pushedMessageCount
+ " messages."
};
response.complete(200);
}
});
})
.catch(function(error){
response.body = error;
response.complete(400);
});
}
The body of the request must have a winningTeam
property. For example:
{
"winningTeam": "Boston Red Sox"
}
Users are expected to have a givenName
property and a favoriteTeam
property.
The Push notification will be similar to:
Joe, the Kansas City Royals just won!
Disabling Push Notifications
The unregister operation allows you to remove the current device from the user account's list of registrations, effectively stopping the user from receiving push notifications on the device. The operation is useful when the user has opted out of receiving this kind of notifications or for another reason. Unregister requires an active user. It will return an error if you call it after logging out the user.
myClient.push(FCMService.class).disablePush();