forked from priteshrnandgaonkar/react-native-call-detection
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
70 lines (63 loc) · 2.6 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
* @providesModule react-native-call-detection
*/
import {
NativeModules,
NativeEventEmitter,
Platform,
PermissionsAndroid
} from 'react-native'
export const permissionDenied = 'PERMISSION DENIED'
const BatchedBridge = require('react-native/Libraries/BatchedBridge/BatchedBridge')
const NativeCallDetector = NativeModules.CallDetectionManager
const NativeCallDetectorAndroid = NativeModules.CallDetectionManagerAndroid
var CallStateUpdateActionModule = require('./CallStateUpdateActionModule')
BatchedBridge.registerCallableModule('CallStateUpdateActionModule', CallStateUpdateActionModule)
const requestPermissionsAndroid = async (permissionMessage) => {
await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE)
.then(async (gotPermission) => gotPermission
? true
: await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE, permissionMessage)
.then((result) => result === PermissionsAndroid.RESULTS.GRANTED)
)
}
class CallDetectorManager {
subscription;
callback
constructor(callback, readPhoneNumberAndroid = false, permissionDeniedCallback = ()=>{}, permissionMessage = {
title: 'Phone State Permission',
message: 'This app needs access to your phone state in order to react and/or to adapt to incoming calls.'
}) {
this.callback = callback
if (Platform.OS === 'ios') {
NativeCallDetector && NativeCallDetector.startListener()
this.subscription = new NativeEventEmitter(NativeCallDetector)
this.subscription.addListener('PhoneCallStateUpdate', callback);
}
else {
if(NativeCallDetectorAndroid) {
if(readPhoneNumberAndroid) {
requestPermissionsAndroid(permissionMessage)
.then((permissionGranted) => {
if (!permissionGranted) {
permissionDeniedCallback(permissionDenied)
}
})
.catch(permissionDeniedCallback)
}
NativeCallDetectorAndroid.startListener();
}
CallStateUpdateActionModule.callback = callback
}
}
dispose() {
NativeCallDetector && NativeCallDetector.stopListener()
NativeCallDetectorAndroid && NativeCallDetectorAndroid.stopListener()
CallStateUpdateActionModule.callback = undefined
if(this.subscription) {
this.subscription.removeAllListeners('PhoneCallStateUpdate');
this.subscription = undefined
}
}
}
export default module.exports = CallDetectorManager;