Suggestions

close search

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 onIncomingCall event 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.

overview

Push flow

This tutorial will walk you through the steps of integrating push notification into your app to receive Stringee push message.

Overview

Stringee supports Push Notification via Firebase Cloud Messaging (Android) and Voip Notification APNS(iOS). First you get registration token for Push Notification from Firebase or APNS. Then you call Stringee API to register this token to Stringee server. Follow these steps:

1. Setup for iOS

Callkit and Pushkit

The Callkit framework supports iOS 10 and above. Callkit lets Display the system-calling UI for your app's VoIP services, and coordinate your calling services with other apps and the system. For more information, see Callkit

The Pushkit framework supports iOS 8.0 and above. Pushkit sends specific types of notifications such as VoIP invitations, watchOS complication updates, and file provider change notifications... It's very useful for VoIP apps. For more information, see Pushkit

With Callkit and Pushkit support, you can display an incoming call:

Callkit

Callkit

1.1 Create an iOS app on Stringee Dashboard.

Go to Stringee dashboard, choose Push Notification -> Choose your project -> Choose your existing app or create a new app. Enter App name and Package name: Callkit

1.2 Configure Pushkit

1.2.1. Create an APNs Auth Key

To integrate push notification, you must upload an APNs Auth Key. When sending push notifications using an APNs Auth Key, we require the following information about your app:

To create an APNs auth key, follow the steps below.
Visit the Apple Developer Member Center

Callkit

Click on “Certificates, Identifiers & Profiles”. Go to Keys from the Left Menu. Create a new Auth Key by clicking on the “+” button in the top right corner.

Callkit

On the following page, add a Key Name, and select APNs

Callkit

Hit the Continue button.

Callkit

On this page, you will be able to download your auth key file. Please do not rename this file, and upload it as it is to our dashboard, as shown later below.

Callkit

Locate and copy your Team ID – click on your name/company name at the top right corner, then select “View Account”.

Callkit

Copy Team ID. Then go to the iOS app on Stringee dashboard and upload the APNs Auth Key. Click "Upload" button ==> Choose your APNs Auth Key, enter Key ID, Team Id ==> Upload.

Callkit

1.2.2 Configure Pushkit in react native

To use Pushkit in react native, there are 2 options:

In this tutorial, we use react-native-voip-push-notification to work with Callkit framework. Check out their documentation for usage.

Note:

Enable Push Notifications in Capabilities

Callkit

Enable Voice over IP in Capabilities -> Background Modes

Callkit

In Xcode 9, you must add a Info.plist file

  <key>UIBackgroundModes</key>
  <array>
      <string>voip</string>
  </array>
1.2.3 Register to receive notifications with Stringee server

After got the device token, register it to Stringee server

...

import { StringeeClient } from "stringee-react-native";
import VoipPushNotification from "react-native-voip-push-notification";

...

class MyComponent extends React.Component {

...

  componentWillMount() { // or anywhere which is most comfortable and appropriate for you
    VoipPushNotification.requestPermissions(); // required

    VoipPushNotification.addEventListener('register', (token) => {
      // send token to your apn provider server
      this.refs.client.registerPush(
        token,
        false, // isProduction: false: In development, true: In Production.
        true, // (iOS) isVoip: true: Voip PushNotification. Stringee supports this push notification.
        (status, code, message) => {
          console.log(message);
        }
      );
    });

    VoipPushNotification.addEventListener('notification', (notification) => {
        // Invoked when receiving an incoming call. You do nothing here. Notificatin only wakes up app. When the app is active, you can handle the call via "incomingCall" event.   
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <StringeeClient ref="client" eventHandlers={this.clientEventHandlers} />
      </View>
    );
  }

...

}

2. Set up for Android

2.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/

Create a FireBase project

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

Add FireBase to Android app

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

Download google-services.json file

2.2. Set up your project for push notification

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

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

Stringee app

2.3. Set up Firebase and add FCM SDK to your app

Copy google-services.json (From step 2.1) file into the android/app directory.

Add the dependency to android/build.gradle:

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:3.1.1' // google-services plugin
    }
}
allprojects {
    // ...
    repositories {
        // ...
        maven {
            url "https://maven.google.com" // Google's Maven repository
        }
    }
}

Add the plugin at the bottom line of android/app/build.gradle:

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

Add the FCM dependency to android/app/build.gradle file:

dependencies {
     compile 'com.google.firebase:firebase-messaging:15.0.0'
}
2.4. React native FCM

You can use react-native-fcm wrapper for Firebase Cloud Messaging: https://github.com/evollu/react-native-fcm

2.5. 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:

import FCM from "react-native-fcm";
...
const token = FCM.getFCMToken();
Register the registration token to Stringee Server

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

class MyComponent extends React.Component {

...

  componentWillMount() { // or anywhere which is most comfortable and appropriate for you        
      this.refs.client.registerPush(
        token,
        false, // only for iOS
        false, // only for iOS
        (status, code, message) => {
          console.log(message);
        }
      );
  }

  render() {
    return (
      <View style={styles.container}>
        <StringeeClient ref="client" eventHandlers={this.clientEventHandlers} />
      </View>
    );
  }

...

}
Monitor token generation

To handle the creation, rotation, and updating of registration tokens, call:

FCM.on(FCMEvent.RefreshToken, token => {
        this.refs.client.registerPush(
          token,
          true,
          true,
          (result, code, desc) => {}
        );
      });

Make sure you call the registerPush method to register the new token to Stringee server.

2.6. Receive messages

To receive messages, use a service that extends MessagingService.Your service should override the onMessageReceived and onDeletedMessages callbacks. To use MessagingService, you need to add the following in your android/app/src/main/AndroidManifest.xml:

<service
    android:name=".MyFirebaseMessagingService">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT"/>
    </intent-filter>
</service>
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 "incomingCall" event. If the app is killed, you must wake it up and connect to Stringee Server to receive the incoming call. You can do it by starting an ReactActivity in onMessageReceived, then start React application in ReactActivity and connect to Stringee Server in the main entry of the application:

public class MyFirebaseMessagingService extends MessagingService {
    private final String TAG = "Stringee";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            String pushFromStringee = remoteMessage.getData().get("stringeePushNotification");
            if (pushFromStringee != null) { // Receive push notification from Stringee Server
                // Connect to Stringee Server here

                String data = remoteMessage.getData().get("data");
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String callStatus = jsonObject.getString("callStatus");
                    if (callStatus != null && callStatus.equals("started")) {
                        StringeeClient client = StringeeManager.getInstance().getClient();
                        if (client == null || !client.isConnected()) {
                            Intent i = new Intent(this, MyReactActivity.class);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(i);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class MyReactActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .addPackage(new RNStringeeReactPackage())
                .addPackage(new FIRMessagingPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        // The string here (e.g. "MyReactNativeApp") has to match
        // the string in AppRegistry.registerComponent() in index.js
        mReactRootView.startReactApplication(mReactInstanceManager, "OneToOneCallSample", null);

        setContentView(mReactRootView);
    }
}

Remember to declare MyReactActivity in android/app/src/main/AndroidManifest.xml:

<activity android:name=".MyReactActivity" />

Note

You should register push notification when you connect Stringee server first time:

    this.refs.client.registerPush(
        token,
        false, // isProduction: false: In development, true: In production.
        true, // (iOS) isVoip: true: Voip PushNotification. Stringee supports this push notification.
        (status, code, message) => {
          console.log(message);
        }
    );

When you no longer want to receive push notification from Stringee server, you must call:

    this.refs.client.unregisterPush(
        token,
        (status, code, message) => {
          console.log(message);
        }
    );

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