How to Detect Call States in React Native App

Detect Call States in React Native

In this example, you will see how to detect call states in React Native App. This call detection example will help you to detect different call states like IncomingDisconnectedDialing and Connected for iOS. For android, this will give the following states, Offhook, Incoming, Disconnected and Missed. In the case of Incoming for Android, you can also get the incoming phone number.

How to Detect Call States

For the call state detection, we are going to use react-native-call-detection library. This library will provide the following events

iOS events

  1. Connected – Call got connected
  2. Disconnected – Call got disconnected
  3. Dialing – When we dial a number
  4. Incoming – While getting an incoming call

Android events

  1. Offhook – At least one call exists that is dialing, active, or on hold, and no calls are ringing or waiting.
  2. Disconnected – Call got disconnected
  3. Incoming – While getting an incoming call
  4. Missed – Call got missed

Here is the code snippet which will help us to detect the call state

let callDetector = new CallDetectorManager(
  (event, number) => {
    console.log('event -> ', event + (number ? ' - ' + number : ''));
    var updatedCallStates = callStates;
    updatedCallStates.push(event + (number ? ' - ' + number : ''));
    setFlatListItems(updatedCallStates);
    setCallStates(updatedCallStates);

    // For iOS event will be either "Connected",
    // "Disconnected","Dialing" and "Incoming"

    // For Android event will be either "Offhook",
    // "Disconnected", "Incoming" or "Missed"
    // phoneNumber should store caller/called number

    if (event === 'Disconnected') {
        // Do something call got disconnected
    } else if (event === 'Connected') {
        // Do something call got connected
        // This clause will only be executed for iOS
    } else if (event === 'Incoming') {
        // Do something call got incoming
    } else if (event === 'Dialing') {
        // Do something call got dialing
        // This clause will only be executed for iOS
    } else if (event === 'Offhook') {
        //Device call state: Off-hook.
        // At least one call exists that is dialing,
        // active, or on hold,
        // and no calls are ringing or waiting.
        // This clause will only be executed for Android
    } else if (event === 'Missed') {
        // Do something call got missed
        // This clause will only be executed for Android
    }
  },
  true, // True if you want to read the phone number of the incoming call [ANDROID]
  () => {
    console.log('Permission Denied by User');
  }, // callback if your permission got denied [ANDROID] [only if you want to read incoming number] default: console.error
  {
    title: 'Phone State Permission',
    message:'This app needs access to your phone state in order to react and/or to adapt to incoming calls.',
  }
);

Project Overview

In this example, we will have a button to enable and disable the CallDetectorManager with a callback. This detector will keep an eye on the call activity and will provide the event in the callback function. In this callback function, we will update the data source for the list which holds all the events logs.

I hope you are now aware of what we are going to do. Now let’s start with the example.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Installation of Dependency

To use CallDetectorManager we need to install react-native-call-detection package. To install this open the terminal and jump into your project

cd ProjectName

Run the following command

npm install react-native-call-detection --save

This command will copy all the dependencies into your node_module directory, You can find the directory in node_module the directory named react-native-call-detection.

Installation of Pod

React Native 0.60 brings the auto-linking feature which links the library automatically and you just need to install the pod file using the following command

cd ios && pod install && cd ..

Allow Backup for Android App

This is a library dependent configuration that you have to do for Android only. This library needs allowBackup option to be true in your AndroidManifest.xml So open  YourProject/android/app/main/AndroidManifest.xml  and edit android:allowBackup=”false” to android:allowBackup=”true” and save it.

Android Permission to Access Contact List

We are detecting the call state which is sensitive information so we need to add some permission into the AndroidManifest.xml file. Please add the following permissions in your AndroidMnifest.xml.

Go to YourProject -> android -> app -> main -> AndroidMnifest.xml

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
PermissionPurpose
READ_PHONE_STATETo React Phone State


For more about the permission, you can see this post.

Code to Detect Call States

App.js

Open App.js in any code editor and replace the code with the following code

/* How to Detect Call States in React Native from https://aboutreact.com/ */
/* https://aboutreact.com/detect-call-states/ */

//Import React
import React, { useState } from 'react';

//Import required component
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Linking,
  FlatList,
  SafeAreaView,
  Image,
} from 'react-native';

//Import Call Detector
import CallDetectorManager from 'react-native-call-detection';

const App = () => {
  //to keep callDetector reference
  let callDetector = undefined;

  let [callStates, setCallStates] = useState([]);
  let [isStart, setIsStart] = useState(false);
  let [flatListItems, setFlatListItems] = useState([]);

  const callFriendTapped = () => {
    Linking.openURL('tel:5555555555').catch(err => {
      console.log(err);
    });
  };

  const startStopListener = () => {
    if (isStart) {
      console.log('Stop');
      callDetector && callDetector.dispose();
    } else {
      console.log('Start');
      callDetector = new CallDetectorManager(
        (event, number) => {
          console.log('event -> ', event + (number ? ' - ' + number : ''));
          var updatedCallStates = callStates;
          updatedCallStates.push(event + (number ? ' - ' + number : ''));
          setFlatListItems(updatedCallStates);
          setCallStates(updatedCallStates);

          // For iOS event will be either "Connected",
          // "Disconnected","Dialing" and "Incoming"

          // For Android event will be either "Offhook",
          // "Disconnected", "Incoming" or "Missed"
          // phoneNumber should store caller/called number

          if (event === 'Disconnected') {
            // Do something call got disconnected
          } else if (event === 'Connected') {
            // Do something call got connected
            // This clause will only be executed for iOS
          } else if (event === 'Incoming') {
            // Do something call got incoming
          } else if (event === 'Dialing') {
            // Do something call got dialing
            // This clause will only be executed for iOS
          } else if (event === 'Offhook') {
            //Device call state: Off-hook.
            // At least one call exists that is dialing,
            // active, or on hold,
            // and no calls are ringing or waiting.
            // This clause will only be executed for Android
          } else if (event === 'Missed') {
            // Do something call got missed
            // This clause will only be executed for Android
          }
        },
        true, // True if you want to read the phone number of the incoming call [ANDROID]
        () => {
          console.log('Permission Denied by User');
        }, // callback if your permission got denied [ANDROID] [only if you want to read incoming number] default: console.error
        {
          title: 'Phone State Permission',
          message:
            'This app needs access to your phone state in order to react and/or to adapt to incoming calls.',
        }
      );
    }
    setIsStart(!isStart);
  };

  const listSeparator = () => {
    return (
      <View
        style={{ height: 0.5, width: '100%', backgroundColor: '#ebebeb' }}
      />
    );
  };

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={styles.container}>
        <View style={styles.header}>
          <Text style={styles.headerTextLarge}>
            Example to detect call states
          </Text>
          <Text style={styles.headerText}>www.aboutreact.com</Text>
        </View>
        <FlatList
          style={{ flex: 1 }}
          data={flatListItems}
          ItemSeparatorComponent={listSeparator}
          renderItem={({ item }) => (
            <View style={{ flex: 1 }}>
              <Text style={styles.callLogs}>{JSON.stringify(item)}</Text>
            </View>
          )}
          keyExtractor={(item, index) => index.toString()}
        />
        <TouchableOpacity style={styles.button} onPress={startStopListener}>
          <Text style={styles.buttonText}>
            {isStart ? 'Stop Listner' : 'Start Listener'}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.7}
          onPress={callFriendTapped}
          style={styles.fabStyle}>
          <Image
            source={{
              uri:
                'https://raw.githubusercontent.com/AboutReact/sampleresource/master/input_phone.png',
            }}
            style={styles.fabImageStyle}
          />
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  header: {
    backgroundColor: '#ff8c21',
    padding: 10,
  },
  headerTextLarge: {
    textAlign: 'center',
    fontSize: 20,
    color: 'white',
  },
  headerText: {
    marginTop: 5,
    textAlign: 'center',
    fontSize: 18,
    color: 'white',
  },
  button: {
    alignItems: 'center',
    backgroundColor: '#ff8c21',
    padding: 10,
    justifyContent: 'center',
    height: 60,
    width: '100%',
  },
  buttonText: {
    textAlign: 'center',
    fontSize: 18,
    color: 'white',
  },
  callLogs: {
    padding: 16,
    fontSize: 16,
    color: '#333333',
  },
  fabStyle: {
    position: 'absolute',
    width: 60,
    height: 60,
    borderRadius: 60 / 2,
    alignItems: 'center',
    justifyContent: 'center',
    right: 30,
    bottom: 30,
    backgroundColor: 'yellow',
  },
  fabImageStyle: {
    resizeMode: 'contain',
    width: 20,
    height: 20,
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

Android

Detect Call State 1   Detect Call State 2    Detect Call State 3    Detect Call State 4   Detect Call State 5

This is how you can detect Calls in React Native. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.