Real-time score alerts
Guided demo
Features described in this document are fully functional in the guided version of the Live Events demo, but not in the public Live Events demo. To see real-time score alerts in action, contact sales for a guided demo.
Live sports events happen in real-time, but fans can't always keep their eyes on the screen. When a crucial goal is scored or a major play happens, notifying offline fans immediately brings them back to the action.
By the end of this document, you will understand how to:
- Implement real-time score alerts using PubNub's push notification system
- Send properly formatted push notifications with current scores
- Set up your mobile application to receive and display sports notifications
How PubNub helps
Role in the solution | PubNub feature (click to learn more!) |
---|---|
| Mobile Push Notifications |
| Pub/Sub Messaging |
| FCM Integration |
Use case overview
This document describes how PubNub sends real-time score alerts to fans who aren't actively watching the game, bringing them back to the action at critical moments.
When a goal is scored, the system delivers push notifications displaying the current score, enticing offline fans to return to the app to see the gameplay.
Key features include:
- Score alerts sent instantly when goals happen
- Current score shown right in the notification
- High-priority delivery for timely updates
- Easy device registration for notifications
- Engaging display that brings fans back
Cross-platform push notifications with PubNub
PubNub enables you to send push notifications to both Android and iOS devices with a single API call. This cross-platform capability eliminates the need to write platform-specific backend code or manage separate systems for different device types. Your server publishes one message, and PubNub handles the delivery to Firebase Cloud Messaging (FCM) for Android and Apple Push Notification service (APNs) for iOS devices.
The screenshots and examples in this documentation focus on Android (using FCM) as it can be demonstrated through web-based emulators, but the same PubNub implementation would deliver to iOS devices with minimal configuration changes.
While the self-led Live Events demo directs you to contact sales for a demonstration of push notifications, the following preview shows what you'll experience in the guided demo:
During your guided demo with our sales team, they will show you how a team scoring a goal will result in a push message being received on the Android emulator. The notification displays the current score SOU 0 - 2 LEE
with the message Leeds Score!
.
The push notification is displayed in two places:
-
The web app (both tablet and mobile view) - this uses PubNub messaging to notify clients that a message has been sent
-
The mobile emulator - this uses an actual mobile push message, sent through Firebase Cloud Messaging via PubNub, and displayed on an Android emulator running in the cloud
These previews demonstrate how PubNub's push notification capabilities deliver real-time score alerts to bring fans back to the action, even when they're not actively watching.
Basic setup for push notifications
The Live Events demo implements push notifications using PubNub's Mobile Push Notification feature integrated with Firebase Cloud Messaging (FCM) for Android devices.
Server-side setup
// Initialize PubNub with push notification capabilities
const pubnub = new PubNub({
publishKey: process.env.PUBNUB_PUBLISH_KEY,
subscribeKey: process.env.PUBNUB_SUBSCRIBE_KEY,
userId: "game-server",
// Secret key is required on the server side for certain push operations
secretKey: process.env.PUBNUB_SECRET_KEY
});
Android client-side setup
// In MainActivity.kt
private fun initializePubNub(userId: String, subscribeKey: String) {
// Create PubNub configuration
this.pubnub = PubNub.create(
PNConfiguration.builder(
UserId(userId),
subscribeKey
).build()
)
// Register for push notifications
getToken() // Retrieve FCM token and register with PubNub
}
This implementation shows the essential components needed to set up push notifications: a server-side PubNub instance for sending notifications and a client-side configuration for receiving them. The specific notification payload structure and how it's triggered will be covered in the following sections.
Backend implementation
The Live Events demo sends formatted push notification messages when goals are scored. These messages are structured specifically for Firebase Cloud Messaging (FCM) to maximize deliverability and engagement.
Create notification payload
When a goal is scored, the demo formats a push notification message with this structure:
{
channel: "game.push-sales",
data: {
text: 'PubNub Push Notification',
pn_fcm: {
data: {
title: 'SOU 0 - 2 LEE',
body: 'Leeds Score!'
},
android: {
priority: 'high',
}
}
}
}
This message uses PubNub's FCM integration with these key elements:
- The
channel
parameter defines where the notification is published. - The
pn_fcm
field contains the FCM-specific payload. title
displays the current score in a clear format.body
announces the goal with a concise message.priority: 'high'
sets the priority as defined by FCM.
When this notification payload is published to the game.push-sales
channel using PubNub's publish API, PubNub delivers it to all registered Android devices that have subscribed to that channel for push notifications - whether those devices are currently online or offline.
Mobile client implementation
The mobile client in the Live Events demo uses Firebase Cloud Messaging (FCM) to receive push notifications sent through PubNub.
Register device for push notifications
The Android app registers the device to receive push notifications when it starts:
// In MainActivity.kt
private fun getToken() {
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
try {
val token = task.result
if (token != null) {
Log.d(logTag, "Retrieved token: $token")
pubnub.addPushNotificationsOnChannels(
pushType = PNPushType.FCM,
deviceId = token,
channels = listOf(pushChannel) // "game.push-sales"
).async { result ->
result.onFailure { exception ->
Log.d(logTag, "Push Registration Failed: $exception")
}.onSuccess {
show all 28 linesThis code:
- Requests a device token from Firebase.
- Uses PubNub's SDK to register this token with PubNub's Mobile Push service via
addPushNotificationsOnChannels()
. - PubNub stores this mapping between the device token and the
game.push-sales
channel on its servers. - PubNub confirms successful registration, allowing the app to update its UI.
When a device token is renewed, the FCMHandler initiates the registration of the new token with PubNub:
// n FCMHandler, which overrides FirebaseMessagingService()
override fun onNewToken(token: String) {
//Called whenever the FCM token is renewed - re-register the device with PubNub
Log.d(logTag, "New Token Received: $token")
pubnub.addPushNotificationsOnChannels(
pushType = PNPushType.FCM,
deviceId = token,
channels = listOf(pushChannel)
).async { result ->
// Handle result
}
}
This direct approach ensures that whenever Firebase refreshes the device token, the new token is immediately registered with PubNub, maintaining uninterrupted push notification capability. For more information and FCM best practices around maintaining token freshness, see Firebase's documentation on ensuring registration token freshness.
Handle incoming notifications
The FCMHandler processes incoming push notifications that were originally sent through PubNub's network:
// In FCMHandler.kt
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
var title : String
var body : String
Log.d(logTag, "Message Received from FCM")
// Handle data payload (works in background and foreground)
if (remoteMessage.data.isNotEmpty()) {
remoteMessage.data.let {
Log.d(logTag, "Message data payload: " + remoteMessage.data)
title = remoteMessage.data["title"].toString()
body = remoteMessage.data["body"].toString()
sendNotification(title, body)
show all 26 linesThese notifications originated from PubNub's system, which forwarded them to FCM based on the device token registration.
Display score notifications
The FCMHandler creates customized notifications for displaying the score data sent through PubNub:
// In FCMHandler.kt
private fun sendNotification(title: String, body: String) {
val notificationID = 101
// Just launch the app if the notification is tapped
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pend = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
val channelID = getString(R.string.default_notification_channel_id)
// Use trophy icon for score notifications
val bm = BitmapFactory.decodeResource(resources, R.drawable.cup)
var builder = NotificationCompat.Builder(this, channelID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
show all 27 linesThis implementation:
- Creates a notification that displays the score data that originated from PubNub.
- Uses a trophy icon consistently for all score notifications.
- Sets up a pending intent that opens the app when tapped.
- Makes the notification dismiss itself when tapped.
The entire flow demonstrates how PubNub acts as the bridge between the server-side score events and the Firebase Cloud Messaging service that ultimately delivers the notifications to Android devices.
Best practices for score alerts
The guided, sales-led Live Events demo implements these best practices for effective score notifications:
-
Clear, concise content: The title
SOU 0 - 2 LEE
immediately shows the score, whileLeeds Score!
explains what happened. -
Visual distinction: Using appropriate icons helps users quickly identify score notifications.
-
Actionable notifications: Tapping the notification opens the app directly.
-
Efficient registration: Properly handling token refreshes ensures reliable delivery.
-
Cross-platform support: In production apps, implement both FCM for Android and APNs for iOS. For iOS, you would use similar PubNub registration methods but with the APNs push gateway:
pubnub.push.addChannels({
channels: ["game.push-sales"],
device: deviceToken,
pushGateway: "apns2",
environment: "production",
topic: "com.your.bundle.id"
});
By following these patterns from the Live Events demo, you can create an effective score alert system that keeps fans engaged with your sports application, even when they're not actively watching.