-
Notifications
You must be signed in to change notification settings - Fork 110
/
index.js
76 lines (67 loc) · 2.66 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
71
72
73
74
75
76
/*
* @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)
// https://stackoverflow.com/questions/13154445/how-to-get-phone-number-from-an-incoming-call : Amjad Alwareh's answer.
const requestPermissionsAndroid = (permissionMessage) => {
const requiredPermission = Platform.constants.Release >= 9
? PermissionsAndroid.PERMISSIONS.READ_CALL_LOG
: PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE
return PermissionsAndroid.check(requiredPermission)
.then((gotPermission) => gotPermission
? true
: PermissionsAndroid.request(requiredPermission, 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((permissionGrantedReadState) => {
if (!permissionGrantedReadState) {
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;