Skip to main content

Android

The Push Notification extension allows you to send push notifications to mobile apps and desktop browsers. In this section, we will see how to send Push Notifications to your Android app using Firebase Cloud Messaging or FCM.

Use Connection Service

If you want to use the System's native call service to handle calls, please refer to our guide on Android - Connection Service

I want to checkout the sample app

Android Push notifications sample app

View on Github

Firebase Project Setup

Visit Firebase Console and login/signup using your Gmail ID.

Step 1: Create a new Firebase Project

On your Firebase Console, create a new project.

Image

This is a simple 3 step process where:

  1. You give a name to your project
  2. Add Google Analytics to your project (Optional)
  3. Configure Google Analytics account (Optional)

Click on Create and you are ready to go.

Step 2: Add Firebase to your Android App

  1. Click on the Android icon as shown on the screen below.
Image
  1. Register your Android app by providing the following details:
    1. Android Package name
    2. App nickname (optional)
    3. Debug signing certificate SHA-1 (optional)
Image
  1. Download the google-services.json file and place it in the required location in your project.
Image
  1. Add Firebase SDK by copying and pasting the snippets in the Project-level build.gradle file.
Image
  1. Add Firebase SDK by copying and pasting the snippets in the App-level build.gradle file.
Image
  1. Click on 'Continue to Console' to finish the setup.

Step 3: Download the service account file

Image

Extension settings

Step 1: Enable the extension

  1. Login to CometChat and select your app.
  2. Go to the Extensions section and Enable the Push Notifications extension.
  3. Open the settings for this extension and save the following.
Image

Step 2: Save your settings

On the Settings page you need to enter the following:

  1. Set extension version
  • If you are setting it for the first time, Select V2 to start using the enhanced version of the Push Notification extension. The enhanced version uses Token-based approach for sending Push Notifications and is simple to implement.
  • If you already have an app using V1 and want to migrate your app to use V2, then Select V1 & V2 option. This ensures that the users viewing the older version of your app also receive Push Notifications.
  • Eventually, when all your users are on the latest version of your app, you can change this option to V2, thus turning off V1 (Topic-based) Push Notifications completely.
  1. Select the platforms that you want to support
  • Select from Web, Android, Ionic, React Native, Flutter & iOS.
  1. Notification payload settings
  • You can control if the notification key should be in the Payload or not. Learn more about the FCM Messages here.
  1. Notification Triggers
Image
  • Select the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
    1. Message Notifications
    2. Call Notifications
    3. Group Notifications
  • These are pretty self-explanatory and you can toggle them as per your requirement.

Android App Setup

In the Firebase Project setup, we did the following things:

  1. Added google-services.json file to the project.
  2. Added the required Firebase SDK snippets to the Project-level build.grade file.
  3. Added the required Firebase SDK snippets to the App-level build.gradle file.

If you want more details, check the Firebase Documentation.

Step 1: Register the FCM Token on user login

  1. Initialize CometChat and then login your user.
  2. On successful login, you can register the obtained FCM Token using CometChat.registerTokenForPushNotification() function call. (You can see the process of getting the FCM Token in the next step)
CometChat.registerTokenForPushNotification(MyFirebaseMessagingService.token, new CometChat.CallbackListener<String>() {
@Override
public void onSuccess(String s) {
Log.e( "onSuccessPN: ",s );
}
@Override
public void onError(CometChatException e) {
Log.e("onErrorPN: ",e.getMessage() );
}
});

To fetch the registered token you can use below Firebase method.

FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(
new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
if (!task.isSuccessful()) {
return;
}
token = task.getResult().getToken();
//CometChat.registerTokenForPushNotification(token, CometChat.CallbackListener<String>());
}
});

Step 2: Receive notifications

  1. The FCM Token can be received by overriding the onNewToken() method. This token is stored as a String variable. You can choose to store it in SharedPreferences as well.
  2. To receive messages, you need to override the onMessageReceived(RemoteMessage remoteMessage).
  3. PushNotificationService.java has the code that provides a way you can handle messages received from CometChat users and groups.
  4. CallNotificationAction.class is a BroadcastReceiver which is used to handle call events when your app is in the background state.
  5. Since Android O, there have been certain restrictions added for background tasks and users cannot launch intent directly from the service. More details here.
  6. We suggest you to create notification channel inside your application class. After Android O, it is necessary to register notification channel to allow notifications of your apps.
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel("2", name, importance);
channel.setDescription(description);
channel.enableVibration(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
  • You also need to add both of the above-mentioned files in your AndroidManifest.xml to make Push notification work in the background as well.
<service
android:name=".MyFirebaseMessagingService"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<receiver android:name=".CallNotificationAction" />

Advanced

Sending Custom Notification body

Push notification has 2 parts, namely, the notification title and notification body. The title can be: a. Name of the sender in case of one-on-one message. (E.g.: Spiderman) b. Name of the sender followed by group name for group messages (E.g.: Spiderman @ ComicHeros)

The body of the message depends upon the type of message being sent. You can send a custom body by specifying the pushNotification key followed by some user-defined string for the notification body inside metadata while sending the message.

The following code shows an example of a Custom body using a message of category=custom. This is however not just limited to a custom category of messages.

String receiverId="superhero1";
JSONObject metaData=new JSONObject();
JSONObject customData=new JSONObject();

try {
metaData.put("pushNotification","Custom Notification body");
customData.put("yourkey","Your Value");
} catch (JSONException e) {
e.printStackTrace();
}

CustomMessage customMessage=new CustomMessage(receiverId,CometChatConstants.RECEIVER_TYPE_USER,customData);
customMessage.setMetadata(metaData);

CometChat.sendCustomMessage(customMessage, new CometChat.CallbackListener<CustomMessage>() {
@Override
public void onSuccess(CustomMessage customMessage) {
Log.d(TAG, "onSuccess: "+customMessage.toString());
}

@Override
public void onError(CometChatException e) {
Log.d(TAG, "onError: "+e.getMessage());
}
});

Converting Push Notification Payloads to Message Objects

CometChat provides a method CometChatHelper.processMessage() to convert the message JSON to the corresponding object of TextMessage, MediaMessage, CustomMessage, Action or Call.

This code needs to be added to the onMessageReceived() method of the FirebaseMessagingService class.

CometChatHelper.processMessage(new JSONObject(remoteMessage.getData().get("message"));
info

Type of Attachment can be of the following the type
CometChatConstants.MESSAGE_TYPE_IMAGE
CometChatConstants.MESSAGE_TYPE_VIDEO
CometChatConstants.MESSAGE_TYPE_AUDIO
CometChatConstants.MESSAGE_TYPE_FILE

Push Notification Payload sample for text and media messages-

{
"alert": "Spiderman: Text Message",
"sound": "default",
"title": "CometChat",
"message": {
"receiver": "superhero4",
"data": {
"entities": {
"receiver": {
"entityType": "user",
"entity": {
"uid": "superhero4",
"role": "default",
"name": "Wolverine",
"avatar": "http://data.cometchat.com/assets/images/avatars/wolverine.png",
"status": "offline"
}
},
"sender": {
"entityType": "user",
"entity": {
"uid": "superhero3",
"role": "default",
"name": "Spiderman",
"avatar": "https://data.cometchat.com/assets/images/avatars/spiderman.png",
"status": "offline"
}
}
},
"text": "Text Message"
},
"sender": "superhero3",
"receiverType": "user",
"id": "142",
"sentAt": 1555668711,
"category": "message",
"type": "text"
}
}

Handle Push Notification Actions.

Image

Step 1. Process push notification payload and grab BaseMessage object

To open a chat view, firstly you will need a BaseMessage object. You can grab this from the push notification payload received in onMessageReceived(RemoteMessage message). You need to call CometChat.processMessage() method to process push notification payload.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
try {
JSONObject messageData = new JSONObject(remoteMessage.getData().get("message"));
BaseMessage baseMessage = CometChatHelper.processMessage(messageData);

//Process BaseMessage and show Notification
} catch (JSONException e) {
e.printStackTrace();
}
}

Step 2 . Handle Notification Actions

You can launch the chat view after you tap on the Message Notification by creating PendingIntent and set it with NotificationBuilder object.

info

CometChatMessageListActivity is part of UI Kit Library. You can replace CometChatMessageListActivity with your required class.