Bluetooth headset detection in React Native
Alexey Korepanov
by Alexey Korepanov
~1 min read

Categories

Tags

How to detect Bluetooth headset connection/disconnection events and the headset name in React Native applications in Android and iOS.

I’ve created react-native-bluetooth-headset-detect module which does exactly that.

First let’s add the module to your project:

npm install react-native-bluetooth-headset-detect --save

or

yarn add react-native-bluetooth-headset-detect

There are two ways of using the module.

If your application use React Hooks, you can import a custom hook from the module:

import { useBluetoothHeadsetDetection } from 'react-native-bluetooth-headset-detect';

const MyComponent = () => {
  const device = useBluetoothHeadsetDetection();
  return (
    <Text>Connected headset: {device}</Text>
  );
};

In case of no headset connected, the hook returns empty string. In case of connected headset it will return its name.

If you don’t want to use hooks, you can get connected device name directly and subscribe for connection-disconnection events:

import {
  getHeadset,
  addListener,
  removeListener,
} from 'react-native-bluetooth-headset-detect';

console.log('Connected device:', getHeadset());
addListener((device) => {
  console.log('Connected device:', device);
});

Again, empty string - no headset, otherwise the headset name.

Please also remember to call removeListener with the original functon as a parameter when you are done.

I have also created a demo project that you can find here: https://github.com/alexkorep/react-native-bluetooth-headset-detect-demo