> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Android   Connection Service

Learn how to send Push Notifications to your Android app using Firebase Cloud Messaging or FCM.

<Card title="I want to checkout the sample app" icon="github" href="https://github.com/cometchat/cometchat-push-notification-app-android/tree/v4-push-notifications-extension">
  Android Push notifications sample app

  View on Github
</Card>

## Firebase Project Setup

Visit [Firebase Console](https://console.firebase.google.com/) and login/signup using your Gmail ID.

### Step 1: Create a new Firebase Project

On your Firebase Console, create a new project.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/rr55t_hLoswcBCG0/images/06ec41e4-1623199646-7ba0cb45f033b090fc49ddb715b0cb2b.png?fit=max&auto=format&n=rr55t_hLoswcBCG0&q=85&s=756ac5617361858690d3b16a0fc2fe89" width="1673" height="698" data-path="images/06ec41e4-1623199646-7ba0cb45f033b090fc49ddb715b0cb2b.png" />
</Frame>

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.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/yj8hatI1RYHMwVPT/images/a97e4e80-1623199648-2ae35edb70153eb724714719fc64c65d.png?fit=max&auto=format&n=yj8hatI1RYHMwVPT&q=85&s=ad7a426d2c81fee0d62665d2c3fc0a28" width="559" height="463" data-path="images/a97e4e80-1623199648-2ae35edb70153eb724714719fc64c65d.png" />
</Frame>

2. Register your Android app by providing the following details:

   1. Android Package name
   2. App nickname (optional)
   3. Debug signing certificate SHA-1 (optional)

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/-G4WbAhFV_nFm5lW/images/50ec55fb-1623199650-f637f75678b8c499486603de2346f1d3.png?fit=max&auto=format&n=-G4WbAhFV_nFm5lW&q=85&s=9657cba83f9eedaac3f4288a22d2f240" width="1008" height="612" data-path="images/50ec55fb-1623199650-f637f75678b8c499486603de2346f1d3.png" />
</Frame>

3. Download the google-services.json file and place it in the required location in your project.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/DHfasVbiAENM-XY2/images/9b3d3095-1623199651-d9506794806367499d7e2ce6fbf7ecbf.png?fit=max&auto=format&n=DHfasVbiAENM-XY2&q=85&s=ab87417846e04903b2fa1a8369e69025" width="693" height="429" data-path="images/9b3d3095-1623199651-d9506794806367499d7e2ce6fbf7ecbf.png" />
</Frame>

4. Add Firebase SDK by copying and pasting the snippets in the Project-level build.gradle file.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/yDKVamMkf61gj3YR/images/e597c8dd-1623199652-e34b0f505c4af36ecd03d49dc0e4f564.png?fit=max&auto=format&n=yDKVamMkf61gj3YR&q=85&s=b5cc23646c421aa1e91b78b748022b2d" width="737" height="605" data-path="images/e597c8dd-1623199652-e34b0f505c4af36ecd03d49dc0e4f564.png" />
</Frame>

5. Add Firebase SDK by copying and pasting the snippets in the App-level build.gradle file.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/J3CEbWtjVM-fUC9K/images/d7a68604-1623199654-49dc03a0cc06cbdcab0573b82485c58c.png?fit=max&auto=format&n=J3CEbWtjVM-fUC9K&q=85&s=69edf2c2a9e85ac114310b143f4f0a0a" width="697" height="449" data-path="images/d7a68604-1623199654-49dc03a0cc06cbdcab0573b82485c58c.png" />
</Frame>

6. Click on 'Continue to Console' to finish the setup.

### Step 3: Download the service account file

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/XXAUCbi4d9er5mBV/images/2836ba6c-cometchat-firebase-get-service-account-3ed293fb42bfd421d5127639f2857277.png?fit=max&auto=format&n=XXAUCbi4d9er5mBV&q=85&s=200185cf059e9d40c351171930997b3c" width="3600" height="2400" data-path="images/2836ba6c-cometchat-firebase-get-service-account-3ed293fb42bfd421d5127639f2857277.png" />
</Frame>

## Extension settings

### Step 1: Enable the extension

1. Login to [CometChat](https://app.cometchat.com/login) 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.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/why4qwLRU92tDIid/images/790e609a-cometchat-extensions-push-notifications-2d0156e297965960863d547589c46044.png?fit=max&auto=format&n=why4qwLRU92tDIid&q=85&s=ed0bc637e0f8f1a1bf9c51be7f32fb68" width="1800" height="1200" data-path="images/790e609a-cometchat-extensions-push-notifications-2d0156e297965960863d547589c46044.png" />
</Frame>

### 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 token-based version of the Push Notification extension.
* 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.

2. **Select the platforms that you want to support**

* Select from Web, Android, Ionic, React Native, Flutter & iOS.

3. **Notification payload settings**

* You can control if the notification key should be in the Payload or not. Learn more about the FCM Messages [here](https://firebase.google.com/docs/cloud-messaging/concept-options).

4. **Push payload message options**

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/h4jICZGdYoXE6-Y1/images/10dbaaf4-cometchat-push-notifications-extension-settings-payload-message-options-28494a3c1ed3d9e7a65dd171d17cb12d.png?fit=max&auto=format&n=h4jICZGdYoXE6-Y1&q=85&s=82769092143343f1404cbdec8cf1d8a2" width="1800" height="1200" data-path="images/10dbaaf4-cometchat-push-notifications-extension-settings-payload-message-options-28494a3c1ed3d9e7a65dd171d17cb12d.png" />
</Frame>

The maximum payload size supported by FCM and APNs for push notifications is approximately 4 KB. Due to the inclusion of CometChat's message object, the payload size may exceed this limit, potentially leading to non-delivery of push notifications for certain messages. The options provided allow you to remove the sender's metadata, receiver's metadata, message metadata and trim the content of the text field.

* The message metadata includes the outputs of the Thumbnail Generation, Image Moderation, and Smart Replies extensions. You may want to retain this metadata if you need to customize the notification displayed to the end user based on these outputs.

5. **Notification Triggers**

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/yDKVamMkf61gj3YR/images/e53ecc4b-cometchat-extensions-push-notification-triggers-f847cdea801fcb44572e67c83d3faf66.png?fit=max&auto=format&n=yDKVamMkf61gj3YR&q=85&s=241c0694c824591072555c32659ff784" width="1800" height="1200" data-path="images/e53ecc4b-cometchat-extensions-push-notification-triggers-f847cdea801fcb44572e67c83d3faf66.png" />
</Frame>

* 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](https://firebase.google.com/docs/cloud-messaging/android/client).

### 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)

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    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() );
        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```kotlin theme={null}
    CometChat.registerTokenForPushNotification(MyFirebaseMessagingService.token, object : CallbackListener<String?>() {
                override fun onSuccess(s: String?) {
                    Log.e("onSuccessPN: ", s)
                }

                override fun onError(e: CometChatException) {
                    Log.e("onErrorPN: ", e.message)
                }
            })
    ```
  </Tab>
</Tabs>

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

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    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>());
        }
    });
    ```
  </Tab>

  <Tab title="Kotlin">
    ```kotlin theme={null}
    FirebaseInstanceId.getInstance().getInstanceId()
       .addOnCompleteListener(object : OnCompleteListener<InstanceIdResult?>() {
         fun onComplete(task: com.google.android.gms.tasks.Task<InstanceIdResult>) {
           if (!task.isSuccessful()) {
             return
           }
           token = task.getResult().getToken()
           //CometChat.registerTokenForPushNotification(token,CometChat.CallbackListener<String?>())
         }
       })
    ```
  </Tab>
</Tabs>

### Step 2: Setup ConnectionService.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-feature-react-native-sdk-quotedmessage-a/_FWwfJpY0a1-Jsg7/images/d88ee39d-1637282570-f33f06ff5a99a2d63f062582949f6845.png?fit=max&auto=format&n=_FWwfJpY0a1-Jsg7&q=85&s=8cac580fc3d3253771bee105337cc074" className="h-[50dvh]" width="1121" height="1879" data-path="images/d88ee39d-1637282570-f33f06ff5a99a2d63f062582949f6845.png" />
</Frame>

**ConnectionService** is an abstract service used to handle VoIP & other calls. It is part of android.telecom package which helps to handle telecom services. ConnectionService can be used either as System-Managed Service where System defined UI is shown to handle the calls. It can also be used as Self-Managed Service where users can show their own calling UI to handle the calls.

*Note - Currently the sample app uses system-managed connection service, So the System UI will be displayed to handle incoming calls.*

Learn more about [ConnectionService](https://developer.android.com/reference/android/telecom/ConnectionService).

| Files                                                                                                                                                                                                                     | Description                                                                                                                                                                                                  |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [CallConnectionService.java](https://github.com/cometchat/cometchat-push-notification-app-android/blob/v4-push-notifications-extension/app/src/main/java/com/cometchat/pushnotificationsample/CallConnectionService.java) | Custom ConnectionService file which is used to handle incoming & outgoing calls. It is used to manages the ConnectionService with your app. It also handles PhoneAccounts and bind it's services to Telecom. |
| [CallConnection.java](https://github.com/cometchat/cometchat-push-notification-app-android/blob/v4-push-notifications-extension/app/src/main/java/com/cometchat/pushnotificationsample/CallConnection.java)               | Custom Connection class which is used to handle the callbacks of ConnectionService. Call backs such as onAnswer(), onReject(), onHold(), etc.                                                                |
| [CallManager.java](https://github.com/cometchat/cometchat-push-notification-app-android/blob/v4-push-notifications-extension/app/src/main/java/com/cometchat/pushnotificationsample/CallConnectionService.java)           | It is used to manages the ConnectionService with your app. It also handles PhoneAccounts and bind it's services to Telecom.                                                                                  |

### Step 3: 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](https://github.com/cometchat/cometchat-push-notification-app-android/blob/v4-push-notifications-extension/app/src/main/java/com/cometchat/pushnotificationsample/PushNotificationService.java) has the code that provides a way you can handle messages received from CometChat users and groups.
4. Since Android O, there have been certain restrictions added for background tasks and users cannot launch intent directly from the service. More details [here](https://developer.android.com/guide/components/activities/background-starts).
5. You also need to add the above-mentioned MyFirebasMessagingService.java fil in your AndroidManifest.xml to make Push notification work in the background as well.

<Tabs>
  <Tab title="XML">
    ```xml theme={null}
    <service
        android:name=".MyFirebaseMessagingService"
        android:exported="true"
        android:enabled="true">
        <intent-filter>
             <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    ```
  </Tab>
</Tabs>

### 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.

<Tabs>
  <Tab title="Java">
    ```java theme={null}
    CometChatHelper.processMessage(new JSONObject(remoteMessage.getData().get("message"));
    ```
  </Tab>
</Tabs>

<Note>
  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`
</Note>

Push Notification Payload sample for text and media messages-

<Tabs>
  <Tab title="Text message">
    ```json theme={null}
    {
      "alert": "Nancy Grace: Text Message",
      "sound": "default",
      "title": "CometChat",
      "message": {
        "receiver": "cometchat-uid-4",
        "data": {
          "entities": {
            "receiver": {
              "entityType": "user",
              "entity": {
                "uid": "cometchat-uid-4",
                "role": "default",
                "name": "Susan Marie",
                "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp",
                "status": "offline"
              }
            },
            "sender": {
              "entityType": "user",
              "entity": {
                "uid": "cometchat-uid-3",
                "role": "default",
                "name": "Nancy Grace",
                "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp",
                "status": "offline"
              }
            }
          },
          "text": "Text Message"
        },
        "sender": "cometchat-uid-3",
        "receiverType": "user",
        "id": "142",
        "sentAt": 1555668711,
        "category": "message",
        "type": "text"
      }
    }
    ```
  </Tab>

  <Tab title="Media message">
    ```json theme={null}
    {
      "alert": "Nancy Grace: has sent an image",
      "sound": "default",
      "title": "CometChat",
      "message": {
        "receiver": "cometchat-uid-4",
        "data": {
          "attachments": [
            {
              "extension": "png",
              "size": 14327,
              "name": "extension_leftpanel.png",
              "mimeType": "image/png",
              "url": "https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
            }
          ],
          "entities": {
            "receiver": {
              "entityType": "user",
              "entity": {
                "uid": "cometchat-uid-4",
                "role": "default",
                "name": "Susan Marie",
                "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp",
                "status": "offline"
              }
            },
            "sender": {
              "entityType": "user",
              "entity": {
                "uid": "cometchat-uid-3",
                "role": "default",
                "name": "Nancy Grace",
                "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp",
                "status": "offline"
              }
            }
          },
          "url": "https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
        },
        "sender": "cometchat-uid-3",
        "receiverType": "user",
        "id": "145",
        "sentAt": 1555671238,
        "category": "message",
        "type": "image"
      }
    }
    ```
  </Tab>
</Tabs>
