Android Bluetooth Module for React Native
Your need to add:
import { NativeModules } from 'react-native'
Then create instance for the module:
const {bt} = NativeModules;
Creating the Native Module (Calling the constructor) enables the bluetooth
const enableBluetooth = () => {
bt.enable();
};
const enableBluetooth = () => {
bt.enable(
(bluetoothStatus) => {
console.log(bluetoothStatus);
);
};
const getPairedDevices = async () => {
try {
bt.getPairedDevices ( Devices => {
console.log('Device List', Devices);
setDeviceList(Devices);
});
} catch (e) {
console.error('getPairedDevices', e);
}
};
const discoverDevices = () => {
bt.doDiscovery(
// cb -> callback
(cb) => {
console.log(cb);
}
);
}
const getDiscoveredDevices = () => {
bt.getDiscoveredDevices(
(devices) => {
console.log(devices);
setDiscoveredDeviceList(devices);
}
);
}
const makeDeviceDiscoverable = () => {
bt.makeDeviceDiscoverable(15, //duration in seconds
(cb) => {
console.log(cb);
});
}
const initiateDiscoveredDvcConnection = (deviceAddress) => {
bt.initiateDiscoveredConnection(deviceAddress);
}
const acceptConnection = () => { bt.acceptConnection(); }
const initiateConnection = (deviceAddress) => { bt.initiateConnection(deviceAddress); }
const sendMessage = () => { bt.sendMessage(text); }
const getMessage = () => {
bt.getMessage((msg)=>{
console.log(msg);
setStr(msg);
})
}
const renderDiscoveredDeviceList = () => {
if (discoveredDeviceList==null) { return; }
return Object.entries(discoveredDeviceList).map(([key, value]) => {
return (
<TouchableOpacity
onPress={() => initiateDiscoveredConnection(key)}
style={{
backgroundColor: '#153484',
marginVertical: 5,
marginHorizontal: 10,
padding: 10,
borderRadius: 20,
}}>
<View key={key}>
<Text style={{color: '#fff'}}>{value}</Text>
</View>
</TouchableOpacity>
);
});
};
const renderPairedDeviceList = () => {
return Object.entries(deviceList).map(([key, value]) => {
return (
<TouchableOpacity
onPress={() => initiateConnection(key)}
style={{
backgroundColor: '#153484',
marginVertical: 5,
marginHorizontal: 10,
padding: 10,
borderRadius: 20,
}}>
<View key={key}>
<Text style={{color: '#fff'}}>{value}</Text>
</View>
</TouchableOpacity>
);
});
};