Push Notifications provide a way to deliver some information to a user while they are not using your app actively. The following use cases can be covered by push notifications:
- Offline messages. Send a chat message when a recipient is offline. In this case, a push notification will be sent automatically if the user is offline.
- Offline calls. Make a video/audio call with offline opponents. In this case, a push notification will be sent manually.
- Requests to contact list. Send requests to add a user to the contact list. In this case, a push notification will be sent manually).
- User tags. Send notifications to specific user groups defined by tags.
Before you begin
- Visit our Key Concepts page to get an overall understanding of the most important QuickBlox concepts.
- Register a QuickBlox account. This is a matter of a few minutes and you will be able to use this account to build your apps.
- Configure QuickBlox SDK for your app. Check out our Setup page for more details.
- Create a user session to be able to use QuickBlox functionality. See our Authentication page to learn how to do it.
Configure Firebase project and API key
To start working with push notifications functionality, you need to configure it.
At first, you should create a Firebase account if you haven't it. Then you should configure your Firebase project and obtain the API key and Sender ID.
- To find your FCM server key and Sender ID , go to your Firebase console => Project Settings => Cloud Messaging.




- Copy your FCM server key to your Dashboard => YOUR_APP => Push Notifications => Settings, select the environment for which you are adding the key and click Save key. Use the same key for development and production zones. The Sender ID will be required in the next section.


Add Firebase to your Project
- As part of enabling Firebase services in your Android application, you need to add the google-services plugin to your project-level
build.gradle
file.
buildscript {
// ...
dependencies {
// ...
classpath 'com.google.gms:google-services:4.1.0'
}
}
- Add FCM dependency. If you use version higher than
11.8.0
, then just add the explicit dependency to your application modulebuild.gradle
.
implementation "com.google.android.gms:play-services-gcm:17.0.0"
implementation "com.google.firebase:firebase-messaging:17.0.0"
implementation "com.google.firebase:firebase-core:17.0.0"
If you use google play services in your project, you should use version
11.8.0
or higher (the version we use in our SDK) as allcom.google.android.gms
libraries must use exactly the same version specification.
- Include gms plugin as the last line in the bottom of your app module
build.gradle
.
apply plugin: 'com.google.gms.google-services'
Make sure that
apply plugin: 'com.google.gms.google-services'
is the last line in the file to avoid compilation errors.
- Download
google-services.json
file from your Firebase Project dashboard and put it into your app folder in your Android project. - Copy Sender ID value following Firebase console => Project Settings => Cloud Messaging.
- Edit your app AndroidManifest file and add your Firebase Sender ID as well as notification type and environment to integrate automatic push subscription.
<meta-data
android:name="com.quickblox.messages.TYPE"
android:value="FCM" />
<meta-data
android:name="com.quickblox.messages.SENDER_ID"
android:value="@string/sender_id" />
<meta-data
android:name="com.quickblox.messages.QB_ENVIRONMENT"
android:value="DEVELOPMENT" />
com.quickblox.messages.TYPE
- can beGCM
orFCM
.com.quickblox.messages.SENDER_ID
- your sender ID from google console (for example, 241750217637).com.quickblox.messages.QB_ENVIRONMENT
- can beDEVELOPMENT
orPRODUCTION
.
- Then you need to setup
QBFcmPushListenerService
andQBFcmPushInstanceIDService
in AndroidManifest.
<service android:name="com.quickblox.messages.services.fcm.QBFcmPushListenerService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="com.quickblox.messages.services.fcm.QBFcmPushInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
Automatic push subscription
QuickBlox Android SDK provides automatic push subscription management. It means that you do not need to bother how to get FCM device token, create push subscription, and what to do with the received data. Thus, you can reduce your code and make it cleaner.
A single user can have up to 10 subscriptions on different devices.
Enable/Disable push subscription
Here you can use a global setting to enable or disable delivery of push notifications. Set this parameter only once.
QBSettings.getInstance().setEnablePushNotification(false);
// By default is true
boolean isEnabled = QBSettings.getInstance().isEnablePushNotification();
QBSettings.getInstance().isEnablePushNotification = true
// By Default is TRUE
boolean isEnabled = QBSettings.getInstance().isEnablePushNotification
Track subscription status
To be aware of what is happening with your push subscription, whether you're subscribed successfully or not, you can use the QBSubscribeListener
. Just add QBSubscribeListener
right after the QBSettings.getInstance().init()
code.
QBPushManager.getInstance().addListener(new QBPushManager.QBSubscribeListener() {
@Override
public void onSubscriptionCreated() {
}
@Override
public void onSubscriptionError(Exception e, int resultCode) {
if (resultCode >= 0) {
// Might be Google play service exception
}
}
@Override
public void onSubscriptionDeleted(boolean delete) {
}
});
QBPushManager.getInstance().addListener(object : QBPushManager.QBSubscribeListener {
override fun onSubscriptionCreated() {
}
override fun onSubscriptionError(e: java.lang.Exception?, resultCode: Int?) {
if (resultCode >= 0) {
// Might be Google play service exception
}
}
override fun onSubscriptionDeleted(deleted: Boolean?) {
}
})
Manual push subscription
If you do not want to use the automatic push subscription feature, then do the following:
- Set
SubscribePushStrategy.NEVER
as the main strategy.
// Default SubscribePushStrategy.ALWAYS
QBSettings.getInstance().setSubscribePushStrategy(SubscribePushStrategy.NEVER)
// Default SubscribePushStrategy.ALWAYS
QBSettings.getInstance().subscribePushStrategy = SubscribePushStrategy.NEVER
In this case, you need to subscribe and unsubscribe manually using the following methods:
SubscribeService.subscribeToPushes(context, false);
SubscribeService.unSubscribeFromPushes(context);
SubscribeService.subscribeToPushes(context, false)
SubscribeService.unSubscribeFromPushes(context)
- And then in your class extended from
QBFcmPushListenerService
you need to handle when the token is refreshed:
@Override
public void onNewToken(String token) {
boolean tokenRefreshed = true;
SubscribeService.subscribeToPushes(context, tokenRefreshed);
}
override fun onNewToken(token: String?) {
val tokenRefreshed = true
SubscribeService.subscribeToPushes(context, tokenRefreshed)
}
Send push notifications
You can manually initiate sending of push notifications to a user/users on any event in your application. To send a push notification, you should use QBEvent
, fill its fields with push notification parameters (payload) and set push recipients.
StringifyArrayList<Integer> userIDs = new StringifyArrayList<>();
for (QBUser user : userList) {
userIDs.add(user.getId());
}
QBEvent event = new QBEvent();
event.setUserIds(userIDs);
event.setEnvironment(QBEnvironment.DEVELOPMENT);
event.setNotificationType(QBNotificationType.PUSH);
event.setPushType(QBPushType.GCM);
HashMap<String, Object> customData = new HashMap<>();
customData.put("data.message", "Hello QuickBlox");
customData.put("data.type", "First QuickBlox Push");
event.setMessage(customData);
QBPushNotifications.createEvents(event).performAsync(new QBEntityCallback<QBEvent>() {
@Override
public void onSuccess(QBEvent qbEvent, Bundle bundle) {
// Event Created
}
@Override
public void onError(QBResponseException e) {
}
});
val userIDs = StringifyArrayList<Int>()
for (user in userList) {
userIDs.add(user.id)
}
val event = QBEvent()
event.userIds = userIDs
event.environment = QBEnvironment.DEVELOPMENT
event.notificationType = QBNotificationType.PUSH
event.pushType = QBPushType.GCM
val customData = HashMap<String, Any>()
customData["data.message"] = "Hello QuickBlox"
customData["data.type"] = "First QuickBlox Push"
event.setMessage(customData)
QBPushNotifications.createEvent(event).performAsync(object : QBEntityCallback<QBEvent> {
override fun onSuccess(qbEvent: QBEvent?, bundle: Bundle?) {
// Event Created
}
override fun onError(e: QBResponseException?) {
}
})
Receive push notifications
To receive push notifications, you should register the BroadcastReceiver
.
BroadcastReceiver pushBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
String from = intent.getStringExtra("from");
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(pushBroadcastReceiver, new IntentFilter("new-push-event"));
val pushBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val message = intent.getStringExtra("message")
val from = intent.getStringExtra("from")
}
}
LocalBroadcastManager.getInstance(this).registerReceiver(pushBroadcastReceiver, IntentFilter("new-push-event"))
Or use the onMessageReceived()
in your class that extends QBFcmPushListenerService
.
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String from = remoteMessage.getFrom();
Map<String, String> data = remoteMessage.getData();
}
override fun onMessageReceived(remoteMessage: RemoteMessage?) {
val from = remoteMessage?.from
val data = remoteMessage?.data
}
Updated about a month ago
What's Next
Custom Objects |