Setting up push notifications in your Android application
-
- UpdatedAug 1, 2024
- 3 minutes to read
- Xanadu
- Developer guides
In addition to the tasks that you must perform on your ServiceNow® instance to configure a push notification, you must also include specific code in your Android application.
Create the NowSDK NowPushService
One of the first things that needs to be done in your application is to retrieve the NowSDK NowPushService. Add code similar to the following snippet early within your main code body.
For additional information on the NowPushSDK.makePushService() method, refer to NowPushSDK - makePushService(instanceURL: URL).
Register the push token
Google Firebase provides a unique push token that identifies the device and application to receive push notifications. In order for an application to receive push notification, you must register this token using the NowPushService. Add a function similar to the following code snippet in your Android application. Ensure that you change PushAppName to the name of your Android application. This application must be registered with your ServiceNow® instance.
For additional information on the registerPushToken() method, refer to NowPushService - registerPushToken(pushToken: String, pushApp: String, successCallback: Runnable, errorCallback: Consumer<Throwable>).
Unregister the push token
You need to unregister the push token whenever the user exits your application, such as when the user logs out. Use code similar to the following code snippet to unregister the push token. Ensure that you change PushAppName to the name of your Android application.
For additional information on the unregisterPushToken() method, refer to NowPushService - unregisterPushToken(pushToken: String, pushApp: String, successCallback: Runnable, errorCallback: Consumer<Throwable>).
Implement the FirebaseMessagingService
You must implement the FirebaseMessagingService
within your application.
To setup and implement this service, follow the instructions in the Android Firebase documentation.
Once setup, override the onMessageReceived() method and pass the
RemoteMessage through to the NowPushService
. If the
NowPushService
recognizes the notification, it will process it and return
the notification object for the application to handle. Currently, the only implemented
notification is NowPushVirtualAgent
. An unknown notification returns a
NotSupportedPushError
object.
For additional information on the handlePush() method, refer to NowPushService - handlePush(remoteMessage: RemoteMessage, successCallback: Consumer<NowPushPayload>, errorCallback: Consumer<Throwable>).
In addition, you must override onNewToken(token: String). Be sure to pass the token through to the pushService.registerPushToken(), similar to what was done in the "Register the push token" section.