Skip to main content

Offline push

Chat supports the integration of Google Firebase Cloud Messaging (FCM). This enables Android developers to use an offline push notification service. The service features low latency, high delivery, high concurrency, and no violation of the users' personal data.

Understand the tech

The following figure shows the basic workflow of Chat:

1655713515869

Assume that User A sends a message to User B, but User B goes offline before receiving it. The Chat server pushes a notification to the device of User B via FCM and temporarily stores this message. Once User B comes back online, the Chat SDK pulls the message from the server and pushes the message to User B using persistent connections.

Prerequisites

Before proceeding, ensure that you meet the following requirements:

  • You have initialized the Chat SDK. For details, see SDK quickstart.
  • You understand the call frequency limit of the Chat APIs supported by different pricing plans as described in Limitations.
  • You have activated the advanced features for push in Agora Console. Advanced features allow you to set the push notification mode, do-not-disturb mode, and custom push template.
    You must contact support@agora.io to disable the advanced features for push as this operation will delete all the relevant configurations.

Integrate FCM with Chat

This section guides you through how to integrate FCM with Chat.

1. Create an Android project in Firebase

  1. Log in to Firebase console, and click Add project.

  2. In the Create a project page, enter a project name, and click Create project.

You can toggle off Enable Google Analytics for this project if this option is not needed.
  1. After the project is ready, click Continue to redirect to the project page, and click the Android icon to register an Android project.

  2. In the Add Firebase to your Android app page, perform the following operations:

    1. In the Register app step, enter an Android package name, app nickname (optional), and debug signing certificate SHA-1 (optional), and click Register app.
    2. In the Download google-services.json step, download google-services.json, move this file into your Android app module root directory, and click Next.
    3. In the Add Firebase SDK step, modify your build.gradle files to use Firebase, and click Next.
    4. In the Next steps step, click Continue to console to go back to the project page.
  3. In the project page, click the Android project you have created.

  4. In the Project settings page, select the Cloud Messaging tab, and locate the Server key and Sender ID.

1649906356504

2. Upload FCM certificate to Agora Console

  1. Log in to Agora Console, and click Project Management in the left navigation bar.

  2. On the Project Management page, locate the project that has Chat enabled and click Config.

  3. On the project edit page, click Config next to Chat.

  4. On the project config page, select Features > Push Certificate and click Add Push Certificate.

  5. In the pop-up window, select the GOOGLE tab, and configure the following fields:

3. Enable FCM in Chat

  1. In the build.gradle file of your project, configure dependencies on the FCM library.

_8
dependencies {
_8
// ...
_8
// Imports the Firebase BoM.
_8
implementation platform('com.google.firebase:firebase-bom:28.4.1')
_8
// Declares the dependencies for the Firebase Cloud Messaging.
_8
// When using the BoM, do not specify versions in Firebase library dependencies.
_8
implementation 'com.google.firebase:firebase-messaging'
_8
}

For Gradle 5.0 and later, BoM is automatically enabled, whereas for earlier versions of Gradle, you need to enable the BoM feature. See Firebase Android BoM and Firebase Android SDK Release Notes for details.
  1. Sync the project with the gradle files, extend FirebaseMessagingService, and register FirebaseMessagingService in the AndroidManifest.xml file of your project.

_19
public class EMFCMMSGService extends FirebaseMessagingService {
_19
private static final String TAG = "EMFCMMSGService";
_19
_19
@Override
_19
public void onMessageReceived(RemoteMessage remoteMessage) {
_19
super.onMessageReceived(remoteMessage);
_19
if (remoteMessage.getData().size() > 0) {
_19
String message = remoteMessage.getData().get("alert");
_19
Log.d(TAG, "onMessageReceived: " + message);
_19
}
_19
}
_19
_19
@Override
_19
public void onNewToken(@NonNull String token) {
_19
super.onNewToken(token);
_19
Log.d(TAG, "onNewToken: " + token);
_19
ChatClient.getInstance().sendFCMTokenToServer(token);
_19
}
_19
}


_7
<service
_7
android:name=".java.MyFirebaseMessagingService"
_7
android:exported="false">
_7
<intent-filter>
_7
<action android:name="com.google.firebase.MESSAGING_EVENT" />
_7
</intent-filter>
_7
</service>

  1. Initialize and enable FCM in the Chat SDK.

_25
ChatOptions options = new ChatOptions();
_25
...
_25
PushConfig.Builder builder = new PushConfig.Builder(this);
_25
// Replaces with your FCM Sender ID.
_25
builder.enableFCM("Your FCM sender id");
_25
// Sets push configurations in the ChatOptions class.
_25
options.setPushConfig(builder.build());
_25
// Initializes the Chat SDK.
_25
ChatClient.getInstance().init(this, options);
_25
// Sets the push listener.
_25
PushHelper.getInstance().setPushListener(new PushListener() {
_25
@Override
_25
public void onError(PushType pushType, long errorCode) {
_25
EMLog.e("PushClient", "Push client occur a error: " + pushType + " - " + errorCode);
_25
}
_25
@Override
_25
public boolean isSupportPush(PushType pushType, PushConfig pushConfig) {
_25
// Sets whether FCM is enabled.
_25
if(pushType == PushType.FCM) {
_25
return GoogleApiAvailabilityLight.getInstance().isGooglePlayServicesAvailable(MainActivity.this)
_25
== ConnectionResult.SUCCESS;
_25
}
_25
return super.isSupportPush(pushType, pushConfig);
_25
}
_25
});

  1. Pass the device token of FCM to the Chat SDK.

_17
// Checks whether FCM is enabled.
_17
if(GoogleApiAvailabilityLight.getInstance().isGooglePlayServicesAvailable(MainActivity.this) == ConnectionResult.SUCCESS) {
_17
return;
_17
}
_17
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
_17
@Override
_17
public void onComplete(@NonNull Task<String> task) {
_17
if (!task.isSuccessful()) {
_17
EMLog.d("PushClient", "Fetching FCM registration token failed:"+task.getException());
_17
return;
_17
}
_17
// Gets a new FCM registration token.
_17
String token = task.getResult();
_17
EMLog.d("FCM", token);
_17
ChatClient.getInstance().sendFCMTokenToServer(token);
_17
}
_17
});

  1. Listen for device token generation.

Rewrite the onNewToken callback of FirebaseMessagingService. Once a device token is generated, this callback passes the new device token to the Chat SDK at the earliest opportunity.


_8
@Override
_8
public void onNewToken(@NonNull String token) {
_8
Log.i("MessagingService", "onNewToken: " + token);
_8
// If you want to send messages to this application instance or manage the subscriptions of this app on the server side, send the FCM registration token to your app server.
_8
if(ChatClient.getInstance().isSdkInited()) {
_8
ChatClient.getInstance().sendFCMTokenToServer(token);
_8
}
_8
}

Set up push notifications

To optimize user experience when dealing with an influx of push notifications, Chat provides fine-grained options for the push notification and do-not-disturb (DND) modes at both the app and conversation levels, as shown in the following table:

ModeOptionAppConversation
Push notification modeALL: Receives push notifications for all offline messages.
MENTION_ONLY: Only receives push notifications for mentioned messages.
NONE: Do not receive push notifications for offline messages.
Do-not-disturb modeSILENT_MODE_DURATION: Do not receive push notifications for the specified duration.
SILENT_MODE_INTERVAL: Do not receive push notifications in the specified time frame.

Push notification mode

The setting of the push notification mode at the conversation level takes precedence over that at the app level, and those conversations that do not have specific settings for the push notification mode inherit the app setting by default.

For example, assume that the push notification mode of the app is set to MENTION_ONLY, while that of the specified conversation is set to ALL. You receive all the push notifications from this conversation, while you only receive the push notifications for mentioned messages from all the other conversations.

Do-not-disturb mode

  1. You can specify both the DND duration and DND time frame at the app level. During the specified DND time periods, you do not receive any push notifications.
  2. Conversations only support the DND duration setting; the setting of the DND time frame does not take effect.

For both the app and all the conversations in the app, the setting of the DND mode takes precedence over the setting of the push notification mode.

For example, assume that a DND time period is specified at the app level and the push notification mode of the specified conversation is set to ALL. The DND mode takes effect regardless of the setting of the push notification mode, that is, you do not receive any push notifications during the specified DND time period.

Alternatively, assume that a DND time period is specified for a conversation, while the app does not have any DND settings and its push notification mode is set to ALL. You do not receive any push notifications from this conversation during the specified DND time period, while the push of all the other conversations remains the same.

Set the push notifications of an app

You can call setSilentModeForAll to set the push notifications at the app level and set the push notification mode and DND mode by specifying the SilentModeParam field, as shown in the following code sample:


_11
// Sets the push notification mode to `MENTION_ONLY` for an app.
_11
SilentModeParam param = new SilentModeParam(SilentModeParam.SilentModeParamType.REMIND_TYPE)
_11
.setRemindType(PushManager.PushRemindType.MENTION_ONLY);
_11
// Sets the DND duration to 15 minutes.
_11
SilentModeParam param = new SilentModeParam(SilentModeParam.SilentModeParamType.SILENT_MODE_DURATION)
_11
.setSilentModeDuration(15);
_11
// Sets the DND time frame from 8:30 to 15:00.
_11
SilentModeParam param = new SilentModeParam(SilentModeParam.SilentModeParamType.SILENT_MODE_INTERVAL)
_11
.setSilentModeInterval(new SilentModeTime(8, 30), new SilentModeTime(15, 0));
_11
// Sets the push notifications at the app level.
_11
ChatClient.getInstance().pushManager().setSilentModeForAll(param, new ValueCallBack<SilentModeResult>(){});

Retrieve the push notification setting of an app

You can call getSilentModeForAll to retrieve the push notification settings at the app level, as shown in the following code sample:


_19
ChatClient.getInstance().pushManager().getSilentModeForAll(new ValueCallBack<SilentModeResult>(){
_19
@Override
_19
public void onSuccess(SilentModeResult result) {
_19
// Retrieves the setting of the push notification mode at the app level.
_19
PushManager.PushRemindType remindType = result.getRemindType();
_19
// Retrieves the Unix timestamp when the DND duration of an app expires.
_19
long timestamp = result.getExpireTimestamp();
_19
// Retrieves the start time specified in the DND time frame at the app level.
_19
SilentModeTime startTime = result.getSilentModeStartTime();
_19
startTime.getHour(); // The start hour of the DND time frame.
_19
startTime.getMinute(); // The start minute of the DND time frame.
_19
// Retrieves the end time specified in the DND time frame at the app level.
_19
SilentModeTime endTime = result.getSilentModeEndTime();
_19
endTime.getHour(); // The end hour of the DND time frame.
_19
endTime.getMinute(); // The end minute of the DND time frame.
_19
}
_19
@Override
_19
public void onError(int error, String errorMsg) {}
_19
});

Set the push notifications of a conversation

You can call setSilentModeForConversation to set the push notifications for the conversation specified by the conversationId and ConversationType fields, as shown in the following code sample:


_8
// Sets the push notification mode to `MENTION_ONLY` for a conversation.
_8
SilentModeParam param = new SilentModeParam(SilentModeParam.SilentModeParamType.REMIND_TYPE)
_8
.setRemindType(PushManager.PushRemindType.MENTION_ONLY);
_8
// Sets the DND duration to 15 minutes.
_8
SilentModeParam param = new SilentModeParam(SilentModeParam.SilentModeParamType.SILENT_MODE_DURATION)
_8
.setSilentDuration(15);
_8
// Sets the push notifications at the conversation level.
_8
ChatClient.getInstance().pushManager().setSilentModeForConversation(conversationId, conversationType, param, new ValueCallBack<SilentModeResult>(){});

Retrieve the push notification setting of a conversation

You can call getSilentModeForConversation to retrieve the push notification settings of the specified conversation, as shown in the following code sample:


_15
ChatClient.getInstance().pushManager().getSilentModeForConversation(conversationId, conversationType, new ValueCallBack<SilentModeResult>(){
_15
@Override
_15
public void onSuccess(SilentModeResult result) {
_15
// Checks whether the push notification mode is set for the specified conversation.
_15
boolean enable = result.isConversationRemindTypeEnabled();
_15
// Retrieves the setting of the push notification mode for the specified conversation.
_15
if(enable){
_15
PushManager.PushRemindType remindType = result.getRemindType();
_15
}
_15
// Retrieves the Unix timestamp when the DND duration of a conversation expires.
_15
long timestamp = result.getExpireTimestamp();
_15
}
_15
@Override
_15
public void onError(int error, String errorMsg) {}
_15
});

Retrieve the push notification settings of multiple conversations

  1. You can retrieve the push notification settings of up to 20 conversations at each call.
  2. If a conversation inherits the app setting or its push notification setting has expired, the returned dictionary does not include this conversation.

You can call getSilentModeForConversations to retrieve the push notification settings of multiple conversations, as shown in the following code sample:


_6
ChatClient.getInstance().pushManager().getSilentModeForConversations(conversationList, new ValueCallBack<Map<String, SilentModeResult>>(){
_6
@Override
_6
public void onSuccess(Map<String, SilentModeResult> value) {}
_6
@Override
_6
public void onError(int error, String errorMsg) {}
_6
});

Clear the push notification mode of a conversation

You can call clearRemindTypeForConversation to clear the push notification mode of the specified conversation. Once the specific setting of a conversation is cleared, this conversation inherits the app setting by default.

The following code sample shows how to clear the push notification mode of a conversation:


_1
ChatClient.getInstance().pushManager().clearRemindTypeForConversation(conversationId, conversationType, new CallBack(){});

Set up display attributes

Set the display attributes of push notifications

You can call updatePushNickname to set the nickname displayed in your push notifications, as shown in the following code sample:


_1
ChatClient.getInstance().pushManager().updatePushNickname("pushNickname");

You can also call updatePushDisplayStyle to set the display style of push notifications, as shown in the following code sample:


_5
// `SimpleBanner` indicates that only "You have a new message" displays.
_5
// To display the message content, set `DisplayStyle` to `MessageSummary`.
_5
PushManager.DisplayStyle displayStyle = PushManager.DisplayStyle.SimpleBanner;
_5
// An asynchronous processing is required for this method.
_5
ChatClient.getInstance().pushManager().updatePushDisplayStyle(displayStyle);

Retrieve the display attributes of push notifications

You can call getPushConfigsFromServer to retrieve the display attributes in push notifications, as shown in the following code sample:


_5
PushConfigs pushConfigs = ChatClient.getInstance().pushManager().getPushConfigsFromServer();
_5
// Retrieves the nickname displayed in push notifications.
_5
String nickname = pushConfigs.getDisplayNickname();
_5
// Retrieves the display style of push notifications.
_5
PushManager.DisplayStyle style = pushConfigs.getDisplayStyle();

Set up push translations

If a user enables the automatic translation feature and sends a message, the SDK sends both the original message and the translated message.

Push notifications work in tandem with the translation feature. As a receiver, you can set the preferred language of push notifications that you are willing to receive when you are offline. If the language of the translated message meets your setting, the translated message displays in push notifications; otherwise, the original message displays instead.

The following code sample shows how to set and retrieve the preferred language of push notifications:


_5
// Sets the preferred language of push notifications.
_5
ChatClient.getInstance().pushManager().setPreferredNotificationLanguage("en", new CallBack(){});
_5
_5
// Retrieves the preferred language of push notifications.
_5
ChatClient.getInstance().pushManager().getPreferredNotificationLanguage(new ValueCallBack<String>(){});

Set up push templates

Chat allows users to use ready-made templates for push notifications.

You can create and provide push templates for users by referring to the following steps:

  1. Log in to Agora Console, and click Project Management in the left navigation bar.

  2. On the Project Management page, locate the project that has Chat enable and click Config.

  3. On the project edit page, click Config next to Chat.

  4. On the project config page, select Features > Push Template and click Add Push Template, and configure the fields in the pop-up window, as shown in the following figure:

1655445229699

Once the template creation is complete in Agora Console, users can choose this push template as their default layout when sending a message, as shown in the following code sample:


_28
// This code sample takes a TXT message as an example. You can use the same approach to set IMAGE messages and FILE messages.
_28
ChatMessage message = ChatMessage.createSendMessage(ChatMessage.Type.TXT);
_28
TextMessageBody txtBody = new TextMessageBody("message content");
_28
message.setTo("6006");
_28
// Sets the push template created in Agora Console as their default layout.
_28
JSONObject pushObject = new JSONObject();
_28
JSONArray titleArgs = new JSONArray();
_28
JSONArray contentArgs = new JSONArray();
_28
try {
_28
// Sets the template name.
_28
pushObject.put("name", "test7");
_28
// Sets the template title by specifying the variable.
_28
titleArgs.put("value1");
_28
//...
_28
pushObject.put("title_args", titleArgs);
_28
// Sets the template content by specifying the variable.
_28
contentArgs.put("value1");
_28
//...
_28
pushObject.put("content_args", contentArgs);
_28
} catch (JSONException e) {
_28
e.printStackTrace();
_28
}
_28
// Adds the push template to the message.
_28
message.setAttribute("em_push_template", pushObject);
_28
// Sets the message callback.
_28
message.setMessageStatusCallback(new CallBack() {...});
_28
// Sends the message.
_28
ChatClient.getInstance().chatManager().sendMessage(message);

What's next

This section includes more versatile push notification features that you can use to implement additional functions if needed.

If the ready-made templates do not meet your requirements, Chat also enables you to customize your push notifications.

Custom fields

The following code sample shows how to add an extension field in push notifications:


_20
// This code sample takes a TXT message as an example. You can use the same approach to set IMAGE messages and FILE messages.
_20
ChatMessage message = ChatMessage.createSendMessage(ChatMessage.Type.TXT);
_20
TextMessageBody txtBody = new TextMessageBody("message content");
_20
// Specifies the username of the receiver.
_20
message.setTo("toChatUsername");
_20
// Sets the extension object.
_20
JSONObject extObject = new JSONObject();
_20
try {
_20
extObject.put("test1", "test 01");
_20
} catch (JSONException e) {
_20
e.printStackTrace();
_20
}
_20
// Adds the extension object.
_20
message.setAttribute("em_apns_ext", extObject);
_20
// Sets the message body.
_20
message.addBody(txtBody);
_20
// Sets the message callback.
_20
message.setMessageStatusCallback(new CallBack() {...});
_20
// Sends the message.
_20
ChatClient.getInstance().chatManager().sendMessage(message);

ParameterDescription
txtBodyThe content of the text message.
toChatUsernameThe username of the receiver.
em_apns_extThe custom key used to add the extension field.
Note: Do not modify the key. Modify the value of the key only.

The following example shows a RemoteMessage object received by the remote user:


_9
{
_9
"message":{
_9
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
_9
"data":{
_9
"alert" : "message content",
_9
"test1" : "test 01"
_9
}
_9
}
_9
}

ParameterDescription
dataThe custom data of the push notification.
alertThe displayed content of the push notification. This value varies based on the setting of DisplayStyle.
test1The custom field of the push notification.

Custom displays

The following code sample shows how to customize the display style in push notifications:


_21
// This code sample takes a TXT message as an example. You can use the same approach to set IMAGE messages and FILE messages.
_21
ChatMessage message = ChatMessage.createSendMessage(ChatMessage.Type.TXT);
_21
TextMessageBody txtBody = new TextMessageBody("message content");
_21
// Specifies the username of the receiver.
_21
message.setTo("toChatUsername");
_21
// Sets the custom push notifications.
_21
JSONObject extObject = new JSONObject();
_21
try {
_21
extObject.put("em_push_title", "custom push title");
_21
extObject.put("em_push_content", "custom push content");
_21
} catch (JSONException e) {
_21
e.printStackTrace();
_21
}
_21
// Adds the extension field.
_21
message.setAttribute("em_apns_ext", extObject);
_21
// Sets the message body.
_21
message.addBody(txtBody);
_21
// Sets the message callback.
_21
message.setMessageStatusCallback(new CallBack() {...});
_21
// Sends the message.
_21
ChatClient.getInstance().chatManager().sendMessage(message);

ParameterDescription
toChatUsernameThe username of the sender.
em_apns_extThe custom key used to add the extension field.
Note: Do not modify the key. Modify the value of the key only.
em_push_titleThe custom key used to specify the custom titles of push notifications.
Note: Do not modify the key. Modify the value of the key only.
em_push_contentThe custom key used to specify the custom displayed content of push notifications.
Note: Do not modify the key. Modify the value of the key only.

The following example shows a RemoteMessage object received by the remote user:


_10
{
_10
"message":{
_10
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
_10
"data":{
_10
"alert" : "push content",
_10
"push_title" : "custom push title",
_10
"push_content" : "custom push content"
_10
}
_10
}
_10
}

ParameterDescription
dataThe custom data of the push notification.
alertThe displayed content of the push notification. This value varies based on the setting of DisplayStyle.
push_titleThe custom title of the push notification.
push_contentThe custom content of the push notification.

Force push notifications

Once you force a push notification to a user, the user receives the message regardless of their settings on the push nosh notification and DND modes.

The following code sample shows how to force a push notification:


_11
// This code sample takes a TXT message as an example. You can use the same approach to set IMAGE messages and FILE messages.
_11
ChatMessage message = ChatMessage.createSendMessage(ChatMessage.Type.TXT);
_11
TextMessageBody txtBody = new TextMessageBody("test");
_11
// Sets the username of the receiver.
_11
message.setTo("toChatUsername");
_11
// Sets the custom extension field.
_11
message.setAttribute("em_force_notification", true);
_11
// Sets the message callback.
_11
message.setMessageStatusCallback(new CallBack() {...});
_11
// Sends a message.
_11
ChatClient.getInstance().chatManager().sendMessage(message);

ParameterDescription
txtBodyThe message body.
toChatUsernameThe username of the receiver.
em_force_notificationWhether to force a push notification.
  • true: Yes
  • false: No