Suggestions

close search

Android Push notification

When a Stringee call is made, Stringee Server pushes a message to the client who receives the call. If the client has already connected to Stringee Server, the incoming call can be received via StringeeConnectionListener.onIncomingCall(StringeeCall stringeeCall) and you can ignore the pushed message. Otherwise (the client disconnects from Stringee Server or the app is killed) the client only receives a message pushed from Stringee Server.

Then the client must connect to Stringee Server to receive the incoming call. This tutorial will walk you through the steps of integrating push notification into your app to receive Stringee push message.

1. Create API project

We're using Firebase Cloud Messaging (FCM) for push notification. So you must create a Firebase project in the Firebase console for Cloud Messaging projects. To create a FireBase project, go to https://console.firebase.google.com/

After creating a new FireBase project, add Firebase to your Android app

After adding app, download a google-services.json file.

2. Set up your project for push notification

Go to Firebase project console, choose Project Settings ==> Cloud Messaging, you'll get the Server key.

Go to Stringee Dashboard, choose Push Notification -> Choose your project -> Choose your app if existing or create new app -> Enter the Server key, project package name.

3. Setup Firebase and add FCM SDK to your app

Copy google-services.json (From step 1) file into the app/ directory of your Android Studio project.

Add the dependency to your project-level build.gradle:

buildscript {
  // ...
  dependencies {
    // ...
    classpath 'com.google.gms:google-services:4.4.0' // google-services plugin
  }
}

allprojects {
  // ...
  repositories {
    // ...
    google()
  }
}

Add the plugin at the bottom line of your app-level build.gradle:

apply plugin: 'com.google.gms.google-services'

In Android Studio, add the FCM dependency to your app-level build.gradle file:

dependencies {
  // Import the Firebase BoM
  implementation platform("com.google.firebase:firebase-bom:32.7.1")
  implementation 'com.google.firebase:firebase-messaging'
}

4. Device registration token

Retrieve the current registration token

On initial startup of your app, the FCM SDK generates a registration token for the client app instance. When you need to retrieve the current token, call

FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
@Override
public void onComplete(@NonNull Task<String> task) {
        if (!task.isSuccessful()) {
        return;
        }

        // Get new FCM registration token
        String token = task.getResult();
        }
        });

This method returns null if the token has not yet been generated.

Register the registration token to Stringee Server

In order to receive push notification, you must register the token to Stringee Server by calling:

stringeeClient.registerPushToken(token, new StatusListener() {
@Override
public void onSuccess() {

        }

@Override
public void onError(StringeeError error) {

        }
        });

When the token is registered to Stringee Server, the onPushTokenRegistered is called:

Make sure that the token is registered to Stringee Server successfully. Otherwise, you can not receive push notification.

5. Receive messages

To receive messages, use a service that extends FirebaseMessagingService. Your service should override the onMessageReceived and onNewToken callbacks. To use FirebaseMessagingService, you need to add the following in your app manifest:

<service
        android:name=".MyFirebaseMessagingService"
        android:enabled="true"
        android:exported="false">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT"/>
  </intent-filter>
</service>
Monitor new token generation

The onNewToken callback of the FirebaseMessagingService service fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token. Make sure you have added the service to your manifest, then call getToken in the context of onNewToken, and register it to Stringee Server again:

@Override
public void onNewToken(@NonNull String token) {
        // Register the token to Stringee Server
        stringeeClient.registerPushToken(token, new StatusListener() {
@Override
public void onSuccess() {
        }
@Override
public void onError(StringeeError error) {
        }
        });
        }
Override onMessageReceived

By overriding the method FirebaseMessagingService.onMessageReceived, you can perform actions based on the received RemoteMessage object. You must check whether the client connects to Stringee Server. If connected, do nothing. Otherwise, the client need connect to Stringee Server and the incoming call is received via StringeeConnectionListener.onIncomingCall(StringeeCall stringeeCall) or StringeeConnectionListener.onIncomingCall2(StringeeCall2 stringeeCall2).

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
        String pushFromStringee = remoteMessage.getData().get("stringeePushNotification");
        if (pushFromStringee != null) {
        // Receive push notification from Stringee Server
        String data = remoteMessage.getData().get("data");
        if (data != null) {
        try {
        JSONObject jsonObject = new JSONObject(data);
        String callStatus = jsonObject.optString("callStatus");
        if (callStatus.equals("started")) {
        // Show your incoming call notification or handle something 
        }
        ...
        } catch (JSONException e) {
        e.printStackTrace();
        }
        }
        }
        }
        }
Display incoming call notification

When you successfully register to receive push and receive an incoming call. Stringee push notification data has the following format:

{
  stringeePushNotification = 1.0,
  data = {
  "callId" : "call-vn-1-QNQBY05CSE-1705021351841",
  "serial" : 1,
  "callStatus" : "started",
  "from" : {
    "number" : "user2",
    "alias" : "user2",
  },
  "to":{
    "number" : "user1",
    "alias" : "user1",
  },
  "projectId": 0000
},
type = CALL_EVENT
}

After receive a notification with callStatus is started, you can show your incoming call notification. This is a simple notification that includes answer and reject actions:

Add these permission to your app's manifest file:

<manifest ...>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> // Require for android 13 or above
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT"/> // For show in full screen mode
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> // For show notification over other app
        ...
        </manifest>

For show notification in android 13 or above, you must request the permission POST_NOTIFICATIONS for user to allow it, see more in android documentation.

NotificationManager notificationManager = context.getSystemService(Yourclass.class);

private String createCallNotificationChannel() {
        String channelId = "Your channel id";
        if (VERSION.SDK_INT >= VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId, "Your channel name", NotificationManager.IMPORTANCE_HIGH);
        channel.setDescription("Your channel description");
        notificationManager.createNotificationChannel(channel);
        }
        return channelId;
        }

public void showIncomingCallNotification(String from, String fromAlias) {
        String channelId = createCallNotificationChannel();

        int flag = PendingIntent.FLAG_UPDATE_CURRENT;
        if (VERSION.SDK_INT >= VERSION_CODES.S) {
        flag = PendingIntent.FLAG_IMMUTABLE;
        }

        Intent fullScreenIntent = new Intent(context, YourActivity.class); // Set up the activity which you want to show in fullscreen mode
        // Add some data to the Intent if you want to send it to your activity
        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(context, (int) (System.currentTimeMillis() & 0xfffffff), fullScreenIntent, flag);

        Intent actionAnswerIntent = new Intent(context, YourActivity.class); // Set up the class which you want to show when click on answer button
        // Add some data to the Intent if you want to send it to your activity
        PendingIntent actionAnswerPendingIntent = PendingIntent.getActivity(context, (int) (System.currentTimeMillis() & 0xfffffff), actionAnswerIntent, flag);

        Intent actionRejectIntent = new Intent(context, YourActivity.class); // Set up the class which you want to show when click on answer button
        // Add some data to the Intent if you want to send it to your activity
        PendingIntent actionRejectPendingIntent = PendingIntent.getActivity(context, (int) (System.currentTimeMillis() & 0xfffffff), actionRejectIntent, flag);

        // For action when click on answer/reject button, you dont need to push an activity, you can use Service/Receiver... for doing in background  
        // For example action with reject button
        // Intent actionRejectIntent = new Intent(context, MyReceiver.class); // MyReceiver is extend BroadcastReceiver
        // PendingIntent actionRejectPendingIntent = PendingIntent.getBroadcast(context, (int) (System.currentTimeMillis() & 0xfffffff), actionRejectIntent, flag);

        SpannableString answerTitle = new SpannableString("Answer");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        answerTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#57D24D")), 0, answerTitle.length(), 0);
        }

        Spannable endTitle = new SpannableString("Reject");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        endTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#F64D64")), 0, endTitle.length(), 0);
        }

        Builder notificationBuilder = new Builder(context, channelId);
        notificationBuilder.setContentTitle("Incoming call from " + fromAlias);
        notificationBuilder.setContentText(from);
        notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
        notificationBuilder.setOngoing(true); // Set users cannot manually dismiss notifications
        notificationBuilder.setAutoCancel(false); // Make this notification is not automatically dismissed when the user touches it.
        notificationBuilder.setPriority(NotificationCompat.PRIORITY_HIGH);
        notificationBuilder.setCategory(NotificationCompat.CATEGORY_CALL);
        notificationBuilder.addAction(R.drawable.ic_answer_call, answerTitle, actionAnswerPendingIntent); // Add answer action
        notificationBuilder.addAction(R.drawable.ic_end_call, endTitle, actionRejectPendingIntent); // Add reject action
        notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true); // Add fullscreen mode

// For show notification over other app and display like call notification of system
// You must set importal of the channel is IMPORTANCE_HIGH or higher, priority of the notification is PRIORITY_HIGH of higher, category of the notification is CATEGORY_CALL 

final int YOUR_INCOMINGCALL_NOTIFICATION_ID = 11111;
        notificationManager.notify(YOUR_INCOMINGCALL_NOTIFICATION_ID, notificationBuilder.build());
        }

6. Unregister the registration token.

When you no longer want to receive push notification from Stringee server, call the unregisterPushToken method of StringeeClient:

stringeeClient.unregisterPushToken(token, new StatusListener() {
@Override
public void onSuccess() {

        }

@Override
public void onError(StringeeError error) {

        }
        });

Now you complete the tutorial for push notification. You can view the completed sample on: Sample