Hello Friends 👋,

Welcome To Infinitbility! ❤️

This tutorial will help you to detect is headphone connected or not in ios and android, here we will use react-native-device-info ( https://github.com/react-native-device-info/react-native-device-info ) for detection currently headphone connected or not.

Let’s start today tutorial How to detect headphone in react native

Introduction

React Native device info provide isHeadphonesConnected() function to check headphone connected or not it will return only true or false. isHeadphonesConnected() function work in ios and android.

Installation

  • Go to your project directory and install react-native-device-info package using npm.
npm install --save react-native-device-info
  • Link react-native-device-info package if your react native version less then 0.63.
npx react-native link react-native-device-info

Syntax

DeviceInfo.isHeadphonesConnected() function usages syntax.


import DeviceInfo from 'react-native-device-info';


DeviceInfo.isHeadphonesConnected().then((enabled) => {
  if (!enabled) {
    // ...
  }
});

Example

In Below Example, we will use and store isHeadphonesConnected() value on constant and show in application.

React Native Device Info isHeadphonesConnected example

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  SafeAreaView,
} from 'react-native';
import DeviceInfo from 'react-native-device-info';

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      isHeadphonesConnected: false
    }
  }
  

  componentDidMount(){
    DeviceInfo.isHeadphonesConnected().then((enabled) => {
      if (enabled) {
        this.setState({isHeadphonesConnected: true});
      }
    });
  }

  

  render() {
    const { isHeadphonesConnected } = this.state;
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          <Text>Headphone connected to device </Text>
          <Text>{`${isHeadphonesConnected}`}</Text>
        </View>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    marginTop: 20,
    backgroundColor: '#ffffff',
  },
});

export default App;

Output

React Native, DeviceInfo, isHeadphonesConnected, true, Example
React Native, DeviceInfo, isHeadphonesConnected, false, Example

Thanks for Reading…