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 Incoming
, Disconnected
, Dialing
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
- Connected – Call got connected
- Disconnected – Call got disconnected
- Dialing – When we dial a number
- Incoming – While getting an incoming call
Android events
- Offhook – At least one call exists that is dialing, active, or on hold, and no calls are ringing or waiting.
- Disconnected – Call got disconnected
- Incoming – While getting an incoming call
- 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, // To read the phone number of the incoming call [ANDROID]
() => {
// If permission got denied [ANDROID]
// Only If you want to read incoming number
// Default: console.error
console.log('Permission Denied by User');
},
{
title: 'Phone State Permission',
message:'This app needs access to your phone state',
}
);
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 command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
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
.
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install
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 to 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"/>
Permission | Purpose |
---|---|
READ_PHONE_STATE | To 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 App
// 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, // To detect incoming calls [ANDROID]
() => {
// If your permission got denied [ANDROID]
// Only if you want to read incoming number
// Default: console.error
console.log('Permission Denied by User');
},
{
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
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
Android
This is how you can detect Calls in React Native. If you have any doubts or 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. 🙂
awesome bro that ive looking for
Does it work with expo. Tried it on expo. It doesnt work
No, It is not for Expo
I’m unbale to detect the number
iOS do not provide the number in any case for the security reason, android does provide in case of incoming call.
Could not make it work on iOS 14.x?
What permissions are required for iOS 14.x
Haven’t tried it on that. Anybody else tried?
Does it detect call state changes when the app has been in background for a longer period?
Until the phone quits the app forcefully.
Hello, in Android 11 or previous is excellent but in Android 12 doesn’t work 🙁
Hey found this thread may be it can help
https://github.com/priteshrnandgaonkar/react-native-call-detection/issues/105