-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathindex.js
More file actions
44 lines (38 loc) · 1.05 KB
/
Copy pathindex.js
File metadata and controls
44 lines (38 loc) · 1.05 KB
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
import { NativeEventEmitter, NativeModules } from 'react-native';
import { useEffect, useState } from 'react';
const BluetoothHeadsetDetectModule = NativeModules.RNBluetoothHeadsetDetect;
const bluetoothHeadsetDetectEmitter = new NativeEventEmitter(
BluetoothHeadsetDetectModule
);
let device = null;
const listeners = [];
bluetoothHeadsetDetectEmitter.addListener('onChange', ({ devices }) => {
device = devices.length ? devices[0] : null;
listeners.forEach(listener => {
listener(device);
});
});
// Events
export const getHeadset = () => device;
export const addListener = listener => {
listeners.push(listener);
};
export const removeListener = listener => {
const idx = listeners.indexOf(listener);
if (idx === -1) {
return;
}
listeners.splice(idx, 1);
};
// React hook
export const useBluetoothHeadsetDetection = () => {
const [headset, setHeadset] = useState(null);
useEffect(() => {
setHeadset(device);
addListener(setHeadset);
return () => {
removeListener(setHeadset);
};
}, []);
return headset;
};