'How can I check whether the device is connected to bluetooth or not in react native?
I'm creating an app in that checking the mobile is connected to any Bluetooth enabled device if it's connected then I want to perform some action.
I've tried many libraries listed below
- react-native-ble-manager
- react-native-ble-plx
- react-native-bluetooth-serial
- react-native-bluetooth-serial-next etc..
None of these libraries are providing whether the device is connected or not. If they have method isConnected, they always return false if the device is connected or not. For testing, I'm using a bluetooth headset.
Solution 1:[1]
You can use react-native-netinfo, also.
https://github.com/react-native-community/react-native-netinfo
NetInfo.getConnectionInfo().then(data => {
console.log("Connection type", data.type);
console.log("Connection effective type", data.effectiveType);
});
you can check whether the data.type is bluetooth or not. (Only works on android)
Solution 2:[2]
Using react-native-ble-plx you can add a listener to the bluetooth state:
const subscription = manager.onStateChange((state) => {
console.log("Bluetooth state: ", state);
if (state == 'PoweredOn') {
perform_bluetooth_operations();
}
}, true);
perform_bluetooth_operations () {
// this is where you will begin bluetooth operations.
}
This answer will work with both ios and android.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ayesh Nipun |
| Solution 2 | Nathan Dullea |
