Table of contents
- React Native
- Bluetooth Low Energy
- Bluetooth Classic
- Take Care Of
- Install React Native Application
- What Is React Native Ble Plx
- Install react-native-ble-plx
- Android Configuration
- IOS Configuration
- Location & Bluetooth Permission on Android
- Write scan functionality
- Conclusion
- Please Contact Me for More Information
Nowadays, Almost all mobile applications need Bluetooth features to connect and get data from other devices like sensors. So in this article, I will show you how to integrate Bluetooth Low Energy in your next React Native application.
React Native
React Native is an open-source UI software framework created by Meta Platforms, Inc. It is used to develop applications for Android, Android TV, iOS, macOS, tvOS, Web, Windows, and UWP by enabling developers to use the React framework along with native platform capabilities. It is also being used to develop virtual reality applications at Oculus.
Bluetooth Low Energy
The Bluetooth Low Energy (LE) radio is designed for very low power operation. Transmitting data over 40 channels in the 2.4GHz unlicensed ISM frequency band, the Bluetooth LE radio provides developers a tremendous amount of flexibility to build products that meet the unique connectivity requirements of their market. Bluetooth LE supports multiple communication topologies, expanding from point-to-point to broadcast and, most recently, mesh, enabling Bluetooth technology to support the creation of reliable, large-scale device networks. While initially known for its device communications capabilities, Bluetooth LE is now also widely used as a device positioning technology to address the increasing demand for high accuracy indoor location services. Initially supporting simple presence and proximity capabilities, Bluetooth LE now supports Bluetooth® Direction Finding and soon, high-accuracy distance measurement.
Bluetooth Classic
The Bluetooth Classic radio, also referred to as Bluetooth Basic Rate/Enhanced Data Rate (BR/EDR), is a low-power radio that streams data over 79 channels in the 2.4GHz unlicensed industrial, scientific, and medical (ISM) frequency band. Supporting point-to-point device communication, Bluetooth Classic is mainly used to enable wireless audio streaming and has become the standard radio protocol behind wireless speakers, headphones, and in-car entertainment systems. The Bluetooth Classic radio also enables data transfer applications, including mobile printing.
Take Care Of
Like I mentioned before in this post, there are two types of Bluetooth (classic and Low Energy) and explained the difference between the two types.
For more informations i recommended read this article.
One more thing make sure the device you scan is using BLE(Bluetooth Low Energy) or you can install this app to simulate BLE on your phone or another device you want to connect with.
Install React Native Application
I assume you are familiar with react native or already set up your environment.
For this demo app, I will use react-native CLI
Because I don't find any support BLE in expo CLI.
To install a new app in react native using React Native CLI run this command on your terminal:
npx react-native init BleExample
After installation is done run the following command:
yarn start
open a new window in the terminal and run the following command:
yarn android
If the building app got successfully you will get this screen:
Let's clear code a bit, past the code following:
// Libs
import React from 'react';
// React Native Core Components
import {View, Text, StyleSheet} from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Text style={styles.text}>Integrate Bluetooth BLE In React Native </Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#000',
},
text: {
color: '#fff',
},
});
export default App;
What Is React Native Ble Plx
react-native-ble-plx
is a library for Bluetooth Low Energy building in React Native.
Install react-native-ble-plx
yarn add react-native-ble-plx
Android Configuration
Go to android/app/src/main/AndroidManifest.xml and copy past following lines:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission-sdk-23 android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
IOS Configuration
Enter ios
folder and run pod update
Add NSBluetoothAlwaysUsageDescription
in info.plist
file. (it is a requirement since iOS 13)
Location & Bluetooth Permission on Android
Create folder permissions
and add requestPermissionLocation.js
Open requestPermissionLocation.js
and past the following code:
import {PermissionsAndroid} from 'react-native';
const requestLocationPermission = async () => {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Request for Location Permission',
message: 'Bluetooth Scanner requires access to Fine Location Permission',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
};
export default requestLocationPermission;
Write scan functionality
Now the fun stuff should begin, Update App.js
by following code:
// Libs
import React from 'react';
// React Native Core Components
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import {BleManager} from 'react-native-ble-plx';
import requestLocationPermission from './permissions/requestLocationPermission';
const App = () => {
const manager = new BleManager();
const scanDevices = async () => {
const btState = await manager.state();
// test if bluetooth is powered on
if (btState !== 'PoweredOn') {
alert('Bluetooth is not powered on');
return false;
}
// explicitly ask for user's permission
const permission = await requestLocationPermission();
if (permission) {
manager.startDeviceScan(null, null, async (error, device) => {
console.log('Scanning ...');
// error handling
if (error) {
console.log(error);
return;
}
// found a bluetooth device
if (device.name) {
console.log(`${device.name} (${device.id})}`);
}
// stop scan after 5s
setTimeout(() => manager.stopDeviceScan(), 5000);
});
}
return true;
};
return (
<View style={styles.container}>
<TouchableOpacity style={styles.btnContainer} onPress={scanDevices}>
<Text>Start Scanning Device</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#000',
},
btnContainer: {
backgroundColor: '#fff',
padding: 5,
},
});
export default App;
You should see this screen now:
Click on start scanning devices
button and should see this popup:
After you allow this application using Bluetooth permission you will scanning start on the terminal:
Conclusion
You successfully integrate Bluetooth on your React Native Application.
Try this set up on a real device and simulate BLE on a device that you want to scan by using this application or try with real device support BLE.
For more information and other functionality check Docs