React Native

If you are on version 1.2 or below, you would need to upgrade to 1.3 or above to follow the setup. As 1.3 release had breaking changes with respect to setting up of push notifications. We recommend to update to the current latest version.

This guide discusses how to add push notifications for ringing calls to your project. It will discuss both Android and iOS and go through all the necessary steps.

The normal user experience in a ringing app, when a user receives a call, is to show a push notification. The user can then interact with the notification to accept or reject the call. In this guide, you will learn how to set up your React Native app to get push notifications from Stream for the incoming calls that your user will receive.

Android previewiOS preview
Android preview of the Firebase push notification
iOS preview of VoIP notification using Apple Push Notification service (APNs)

Add push provider credentials to Stream

Please follow the below guides for adding appropriate push providers to Stream:

Install Dependencies

Terminal
yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging
yarn add @notifee/react-native
yarn add react-native-callkeep
yarn add react-native-voip-push-notification
npx pod-install

So what did we install precisely?

  • @react-native-firebase/app and @react-native-firebase/messaging for handling incoming Firebase Cloud Messaging notifications on Android.
  • @notifee/react-native - is used to customize and display push notifications.
  • react-native-voip-push-notification for handling incoming PushKit notifications on iOS.
  • react-native-callkeep for reporting incoming calls to iOS CallKit.

iOS-specific setup

Disable Firebase installation

We don’t use Firebase cloud messaging for iOS in the SDK. Unless Firebase is used for other purposes in your app, you can safely remove it from being installed by iOS and avoid the auto-linking. To do that create a file named react-native.config.js in the root of your project and add the following contents:

react-native.config.js
module.exports = {
  dependencies: {
    "@react-native-firebase/app": {
      platforms: {
        ios: null,
      },
    },
    "@react-native-firebase/messaging": {
      platforms: {
        ios: null,
      },
    },
  },
};

Once this is done, pod install must be run again to remove the installed pods.

  1. In Xcode: Click on Build Phases tab, then open Link Binary With Libraries.
  2. Add CallKit.framework
  3. Add Intents.framework (and mark it Optional).

Example of how to use link libraries required for callkeep library

Add header search path for react native callkeep library

  1. In Xcode: Click on Build Settings tab, then search for Header Search Paths.
  2. Add $(SRCROOT)/../node_modules/react-native-callkeep/ios/RNCallKeep.

Example of how to add header search paths that are required for callkeep library

Add background modes

In Xcode: Open Info.plist file and add the following in UIBackgroundModes. By editing this file with the text editor, you should see:

<key>UIBackgroundModes</key>
<array>
  <string>voip</string>
</array>

Enable push notifications

To receive push notifications, enable the Push Notifications capability in the Xcode Project > Signing & Capabilities pane.

Update AppDelegate

Update AppDelegate.m or AppDelegate.mm in Xcode with the following parts for iOS support.

Add headers

At the top of the file, right after ‘#import “AppDelegate.h”’, add the following headers to import and invoke the methods for the required libraries.

#import "RNCallKeep.h"
#import <PushKit/PushKit.h>
#import "RNVoipPushNotificationManager.h"
#import "StreamVideoReactNative.h"

Initialize on app launch

We need to configure the Firebase library, set up the callkeep library and register VoIP at the app launch. To do this, add the following methods to your existing didFinishLaunchingWithOptions method,

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSString *localizedAppName = [[[NSBundle mainBundle] localizedInfoDictionary] objectForKey:@"CFBundleDisplayName"];
  NSString *appName = [[[NSBundle mainBundle] infoDictionary]objectForKey :@"CFBundleDisplayName"];
  [RNCallKeep setup:@{
    @"appName": localizedAppName != nil ? localizedAppName : appName,
    @"supportsVideo": @YES,
    // pass @YES here if you want the call to be shown in calls history in the built-in dialer app
    @"includesCallsInRecents": @NO,
  }];

  [RNVoipPushNotificationManager voipRegistration];

  // the rest
}

Add PushKit methods

Add the following method to process the VoIP token from iOS and send it to the react-native-voip-push-notification library.

// handle updated push credentials
- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(PKPushType)type {
  [RNVoipPushNotificationManager didUpdatePushCredentials:credentials forType:(NSString *)type];
}

The final method to add is the one that gets invoked when there is a VoIP push notification from Stream. When there is a push notification and if the app is in the background, we want to display an incoming call notification. Add the following method to achieve this,

// handle incoming pushes
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion {
  // send event to JS
  [RNVoipPushNotificationManager didReceiveIncomingPushWithPayload:payload forType:(NSString *)type];

  // process the payload
  NSDictionary *stream = payload.dictionaryPayload[@"stream"];
  NSString *uuid = [[NSUUID UUID] UUIDString];
  NSString *createdCallerName = stream[@"created_by_display_name"];
  NSString *cid = stream[@"call_cid"];

  [StreamVideoReactNative registerIncomingCall:cid uuid:uuid];

  [RNVoipPushNotificationManager addCompletionHandler:uuid completionHandler:completion];

  // display the incoming call notification
  [RNCallKeep reportNewIncomingCall: uuid
                             handle: createdCallerName
                         handleType: @"generic"
                           hasVideo: YES
                localizedCallerName: createdCallerName
                    supportsHolding: YES
                       supportsDTMF: YES
                   supportsGrouping: YES
                 supportsUngrouping: YES
                        fromPushKit: YES
                            payload: stream
              withCompletionHandler: nil];
}

Android-specific setup

  1. To create a Firebase project, go to the Firebase console and click on Add project.

  2. In the console, click the setting icon next to Project overview and open Project settings. Then, under Your apps, click the Android icon to open Add Firebase to your Android app and follow the steps. Make sure that the Android package name you enter is the same as the value of android.package from your app.json.

  3. After registering the app, download the google-services.json file and place it inside of your project at the following location: /android/app/google-services.json.

  4. To allow Firebase on Android to use the credentials, the google-services plugin must be enabled on the project. This requires modification to two files in the Android directory. Add the highlighted lines in the relevant files:

/android/build.gradle
buildscript {
  dependencies {
    // ... other dependencies
    classpath 'com.google.gms:google-services:4.3.15'
  }
}
/android/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

The google-services.json file contains unique and non-secret identifiers of your Firebase project. For more information, see Understand Firebase Projects.

Add declarations in AndroidManifest

Add the following in AndroidManifest.xml:

AndroidManifest.xml
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- We declare the permissions needed for using foreground service to keep call alive -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />

<service
    android:name="app.notifee.core.ForegroundService"
    tools:replace="android:foregroundServiceType"
    android:stopWithTask="true"
    android:foregroundServiceType="shortService|dataSync|camera|microphone|connectedDevice" />

The foreground service and its permissions are essential for displaying incoming call notifications when the app is running in the background, as well as for maintaining video and audio calls during background operation. When uploading the app to the Play Store, it is necessary to declare the foreground service permissions in the Play Console and provide an explanation of their usage. This includes adding a link to a video that demonstrates how the foreground service is utilized for video and audio calls. This procedure is required only once. For more details, refer to here.

The permissions to be explained are:

  • android.permission.FOREGROUND_SERVICE_CAMERA - To access camera when app goes to background
  • android.permission.FOREGROUND_SERVICE_MICROPHONE - To access microphone when app goes to background
  • android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE - To access bluetooth headsets when app goes to background
  • android.permission.FOREGROUND_SERVICE_DATA_SYNC - To keep video/audio calls alive when both camera and microphone access permissions were not granted

Request for notification permissions

At an appropriate place in your app, request for notification permissions from the user. Below is a small example of how to request permissions using react-native-permissions library:

import { requestNotifications } from "react-native-permissions";

await requestNotifications(["alert", "sound"]);

Add Firebase message handlers

To process the incoming push notifications, the SDK provides the utility functions that you must add to your existing or new Firebase notification listeners. Below is the snippet of how to add the firebase listeners:

src/utils/setFirebaseListeners.ts
import messaging from "@react-native-firebase/messaging";
import notifee from "@notifee/react-native";
import {
  isFirebaseStreamVideoMessage,
  firebaseDataHandler,
  onAndroidNotifeeEvent,
  isNotifeeStreamVideoEvent,
} from "@stream-io/video-react-native-sdk";

export const setFirebaseListeners = () => {
  // Set up the background message handler
  messaging().setBackgroundMessageHandler(async (msg) => {
    if (isFirebaseStreamVideoMessage(msg)) {
      await firebaseDataHandler(msg.data);
    } else {
      // your other background notifications (if any)
    }
  });

  // on press handlers of background notifications
  notifee.onBackgroundEvent(async (event) => {
    if (isNotifeeStreamVideoEvent(event)) {
      await onAndroidNotifeeEvent({ event, isBackground: true });
    } else {
      // your other background notifications (if any)
    }
  });

  // Optionally: set up the foreground message handler
  messaging().onMessage((msg) => {
    if (isFirebaseStreamVideoMessage(msg)) {
      firebaseDataHandler(msg.data);
    } else {
      // your other foreground notifications (if any)
    }
  });
  //  Optionally: on press handlers of foreground notifications
  notifee.onForegroundEvent((event) => {
    if (isNotifeeStreamVideoEvent(event)) {
      onAndroidNotifeeEvent({ event, isBackground: false });
    } else {
      // your other foreground notifications (if any)
    }
  });
};

The Firebase message handlers

  • The onMessage handler should not be added if you do not want notifications to show up when the app is in the foreground. When the app is in foreground, you would automatically see the incoming call screen.
  • The isFirebaseStreamVideoMessage method is used to check if this push message is a video related message. And only this needs to be processed by the SDK.
  • The firebaseDataHandler method is the callback to be invoked to process the message. This callback reads the message and uses the @notifee/react-native library to display push notifications.

The Notifee event handlers

  • The onForegroundEvent handler should not be added if you did not add foreground notifications above.
  • The isNotifeeStreamVideoEvent method is used to check if the event was a video related notifee event. And only this needs to be processed by the SDK.
  • The onAndroidNotifeeEvent method is the callback to be invoked to process the event. This callback reads the event and makes sure that the call is accepted or declined.

If you had disabled the installation of Firebase on iOS, add the above method only for Android using the Platform-specific extensions for React Native.

For example, say you add the following files in your project:

setFirebaseListeners.android.ts
setFirebaseListeners.ts

The method above must only be added to the file that .android extension. The other file must add the method but do nothing like below:

setFirebaseListeners.ts
export const setFirebaseListeners = () => {
  // do nothing
};

This is to ensure that @react-native-firebase/messaging is only imported on the Android platform.

Setup the push notifications configuration for the SDK

The SDK automatically processes the incoming push notifications once the setup above is done if the push notifications configuration has been set using StreamVideoRN.setPushConfig. Below is an example of how this method can be called,

src/utils/setPushConfig.ts
import {
  StreamVideoClient,
  StreamVideoRN,
} from "@stream-io/video-react-native-sdk";
import { AndroidImportance } from "@notifee/react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { STREAM_API_KEY } from "../../constants";

export function setPushConfig() {
  StreamVideoRN.setPushConfig({
    ios: {
      // add your push_provider_name for iOS that you have setup in Stream dashboard
      pushProviderName: __DEV__ ? "apn-video-staging" : "apn-video-production",
    },
    android: {
      // add your push_provider_name for Android that you have setup in Stream dashboard
      pushProviderName: __DEV__
        ? "firebase-video-staging"
        : "firebase-video-production",
      // configure the notification channel to be used for incoming calls for Android.
      incomingCallChannel: {
        id: "stream_incoming_call",
        name: "Incoming call notifications",
        // This is the advised importance of receiving incoming call notifications.
        // This will ensure that the notification will appear on-top-of applications.
        importance: AndroidImportance.HIGH,
        // optional: if you dont pass a sound, default ringtone will be used
        // sound: <your sound url>
      },
      // configure the functions to create the texts shown in the notification
      // for incoming calls in Android.
      incomingCallNotificationTextGetters: {
        getTitle: (createdUserName: string) =>
          `Incoming call from ${createdUserName}`,
        getBody: (_createdUserName: string) => "Tap to answer the call",
      },
    },
    // add the async callback to create a video client
    // for incoming calls in the background on a push notification
    createStreamVideoClient: async () => {
      // note that since the method is async,
      // you can call your server to get the user data or token or retrieve from offline storage.
      const userId = await AsyncStorage.getItem("@userId");
      const userName = await AsyncStorage.getItem("@userName");
      if (!userId) return undefined;
      // an example promise to fetch token from your server
      const tokenProvider = () =>
        yourServer.getTokenForUser(userId).then((auth) => auth.token);
      const user = { id: userId, name: userName };
      return StreamVideoClient.getOrCreateInstance({
        apiKey: STREAM_API_KEY, // pass your stream api key
        user,
        tokenProvider,
      });
    },
  });
}

Call the created methods outside of the application lifecycle

Call the methods we have created outside of your application cycle. That is, alongside your AppRegistry.registerComponent() method call at the entry point of your application code. This is because the app can be opened from a dead state through a push notification and in that case, we need to use the configuration and notification callbacks as soon as the JS bridge is initialized.

Following is an example,

index.js
import { AppRegistry } from "react-native";
// highlight-next-line
import { setPushConfig } from "src/utils/setPushConfig";
// highlight-next-line
import { setFirebaseListeners } from "src/utils/setFirebaseListeners";
import App from "./App";

// Set push config
// highlight-next-line
setPushConfig();
// Set the firebase listeners
// highlight-next-line
setFirebaseListeners();
AppRegistry.registerComponent("app", () => App);

Disabling push - usually on logout

In some cases you would want to disable push from happening. For example, if user logs out of your app. Or if the user switches. You can disable push like below:

import { StreamVideoRN } from "@stream-io/video-react-native-sdk";

await StreamVideoRN.onPushLogout();

Optional: On Android show full-screen incoming call view when phone is locked

If you want to display a full-screen notification for the incoming call when the phone is locked, please add the following to your main activity:

  <activity
    ...
    android:showWhenLocked="true"
    android:turnScreenOn="true"
  />

In AndroidManifest.xml add the following permission before the <application> section.

<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />

For apps installed on phones running versions Android 13 or lower, the USE_FULL_SCREEN_INTENT permission is enabled by default.

For all apps being installed on Android 14 and above, the Google Play Store revokes the USE_FULL_SCREEN_INTENT for apps that do not have calling or alarm functionalities. Which means, while submitting your app to the play store, if you do declare that ‘Making and receiving calls’ is a ‘core’ functionality in your app, this permission is granted by default on Android 14 and above.

If the USE_FULL_SCREEN_INTENT permission is not granted, the notification will show up as an expanded heads up notification on the lock screen.

Show the incoming and outgoing call UI when app is on the foreground

The last part of the setup for ringing calls is to show the incoming and outgoing call UIs in the app whenever there is a ringing call. If this was not implemented before, please headover to this page of our documentation to implement that.

Troubleshooting

  • During development, you may be facing a situation where push notification is shown but its events like accepting or rejecting a call don’t work. This is because, during hot module reloading the global event listeners may get de-registered. To properly test during development, make sure that you fully restart the app or test in release mode without the metro packager.
  • You can check the “Webhook & Push Logs” section in the Stream Dashboard to see if Notifications were sent by Stream.
  • If you are still having trouble with Push Notifications, please submit a ticket to us at support.

Closed notification behavior on Android

On Android, users can set certain OS-level settings, usually revolving around performance and battery optimization, that can prevent notifications from being delivered when the app is in a killed state. For example, one such setting is the Deep Clear option on OnePlus devices using Android 9 and lower versions.

© Getstream.io, Inc. All Rights Reserved.