QuickBlox Documentation

QuickBlox provides powerful Chat API and SDK to add real-time messaging and video calls to your web and mobile apps. Learn how to integrate QuickBlox across multiple platforms and devices. Check out our detailed guides to make integration easy and fast.

Push Notifications

Learn how to send push notifications to users when they are offline.

Push Notifications provide a way to deliver some information to the user while they are not using your app actively. Also, push notifications are usable when you need to notify a group of users with the same information (notification). The following use cases can be covered additionally with push notifications:

  • Offline messages. Send a chat message when a recipient is offline (a push notification will be sent automatically if the user is offline).
  • Offline calls. Make a video/audio call with offline opponents( a push notification will be sent manually).
  • Requests to contact list. Send requests to add a user to the contact list ( a push notification will be sent manually).
  • User tags. Send notifications to specific user groups defined by tags.

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.

  1. To find your FCM server key, go to your Firebase console => Project Settings => Cloud Messaging section.
  1. 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.

Add Firebase to your Project

  1. 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'
    }
}
  1. Add FCM dependency. If you use version higher than 11.8.0, then just add the explicit dependency to your application module build.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"

🚧

Pay attention

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 all com.google.android.gms libraries must use exactly the same version specification.

  1. Include gms plugin as the last line in the bottom of your app module build.gradle.
apply plugin: 'com.google.gms.google-services'

🚧

Pay attention

Make sure that apply plugin: 'com.google.gms.google-services' is the last line in the file to avoid compilation errors.

  1. Download google-services.json file from your Firebase Project dashboard and put it into your app folder in your Android project.
  2. Copy Sender ID value from your Firebase console.
  1. 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 be GCM or FCM.
  • com.quickblox.messages.SENDER_ID - your sender ID from google console (for example, 241750217637).
  • com.quickblox.messages.QB_ENVIRONMENT - can be DEVELOPMENT or PRODUCTION.
  1. Then you need to setup QBFcmPushListenerService and QBFcmPushInstanceIDService 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.

🚧

Pay attention

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 automatic push subscription feature, then do the following:

  1. 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)
  1. 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

Push Notifications


Learn how to send push notifications to users when they are offline.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.