Searching for Bluetooth devices using React Native

In my project, I am working on scanning HM-10 BLE with a react-native app. To achieve this, I referred to the example provided in Scanning for Bluetooth devices with React Native. So far, the library seems to be successfully installed without any errors during execution.

  1. react-native init reactnativeBLE
  2. npm i --save react-native-ble-manager
  3. npm install
  4. react-native link react-native-ble-manager
  5. react-native run-ios

However, despite following all the steps mentioned above, when I run the code, it is unable to detect any devices. Within my App.js file, I have included the sample code as provided:

import React, { Component } from 'react';
import { 
    AppRegistry,
    ListView,
    NativeAppEventEmitter, 
    View, 
    Text, 
    Button } from 'react-native';
import BleManager from 'react-native-ble-manager';

// Modified the export to default App
class BluetoothScanner extends Component {
    constructor(props){
        super(props);

        const dataSource = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.devices = [];
        this.state = {
            dataSource: dataSource.cloneWithRows(this.devices)
        };
    }

    componentDidMount() {
        console.log('bluetooth scanner mounted');

        NativeAppEventEmitter.addListener('BleManagerDiscoverPeripheral', (data) => 
        {
            let device = 'device found: ' + data.name + '(' + data.id + ')'; 

            if(this.devices.indexOf(device) == -1) {
                this.devices.push(device);
            }

            let newState = this.state;
            newState.dataSource = newState.dataSource.cloneWithRows(this.devices);
            this.setState(newState);
        });

        BleManager.start({showAlert: false})
                  .then(() =>
                        {
                            // Success code 
                            console.log('Module initialized');
                        });
    }

    startScanning() {
       console.log('start scanning');
       BleManager.scan([], 120);
    }

    render() {
        return (
            <View style={{padding: 50 }}>
                <Text>Bluetooth scanner</Text>
                <Button onPress={() => this.startScanning()} title="Start scanning"/>

                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={(rowData) => <Text>{rowData}</Text>}
                />
            </View>
        );
    }
}

Query: Why am I unable to scan BLE devices even after clicking on start scanning? Is there any additional setup required?

I would greatly appreciate any feedback or advice! Thank you in advance :)

Answer №1

Issues may arise due to the following reasons:

  1. Permission
  2. SDK version

PERMISSIONS

(For Android) To address permission concerns on Android, add these lines to your manifest file located at:

android/app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

When running your app for the first time, ensure that the device prompts for necessary permissions. If not, consider runtime permission requests as demonstrated below:

if (Platform.OS === 'android' && Platform.Version >= 23) {
  PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
      if (result) {
        console.log("Permission is OK");
      } else {
        PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
          if (result) {
            console.log("User accept");
          } else {
            console.log("User refuse");
          }
        });
      }
  });
}  

NOTES

In Android API 29 >, you should use "ACCESS_FINE_LOCATION" instead of "ACCESS_COARSE_LOCATION".


SDK VERSION

If troubleshooting various methods still does not resolve the issue, adjusting the SDK version may be beneficial. Consider downgrading from sdk version 29 to 28 as a potential solution.

android/build.gradle

buildscript {
ext {
    buildToolsVersion = "28.0.3"
    minSdkVersion = 18
    compileSdkVersion = 28
    targetSdkVersion = 28
}

Library Reference: https://github.com/innoveit/react-native-ble-manager

Answer №2

For optimal functionality, consider activating both your location and bluetooth simultaneously.

Answer №3

When working with Android API version 29 or higher, it is important to make use of "ACCESS_FINE_LOCATION" instead of "ACCESS_COARSE_LOCATION".

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Pass information from ColdFusion to jQuery

I'm attempting to achieve a similar result as this, but I believe the syntax is not quite right: <cfset details = '{ name: "name", address:"address"}' /> <img data-details='#details#' onClick="DisplayDetails()" /> &l ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

Successfully resolved: Inability to dynamically adjust button color according to its state

Currently I am working on a feature where a button changes color when it is disabled, but also has a custom color when enabled. Here is the code snippet I am using: Despite setting blue text for the button, it remains blue even after becoming disabled. Ho ...

The content of xmlhttp.responseText is not being displayed in the innerHTML

As part of my ongoing effort to enhance my understanding of Ajax for work purposes, I have been following the W3Schools tutorial and experimenting with my Apache2 server. In this process, I have placed a file named ajax_info.txt on the server (in /var/www ...

What is the best method for transferring a string from JavaScript to a JSON file?

Is there a way to update the value of "JSValue" in my JSON (JSValue) using JavaScript? Specifically, how can I assign JSValue to a variable called Value using JavaScript? JavaScript var Value = 1 + 1 JSON { "DATA": [ { "JSValue": "0" } ...

Creating a sticky v-stepper-header while scrolling in VuetifyJS

Can anyone help me figure out how to make the <v-stepper-header> component stay sticky when scrolling? I attempted to create custom CSS for this but was unsuccessful. Below is a snippet of code that I tried: <v-stepper v-model="step"&g ...

Unable to automate the selection of a dropdown menu using Selenium WebDriver

I am currently utilizing http://www.makemytrip.com/ This is the HTML code. <div class="mrgnBot30 clearFix"> <span class="watch_icn flL"></span> <div class="widget_inner clearFix suggest_me padBot15 flL"> <h3 class="clearFix has ...

What is the best way to create an Office Script autofill feature that automatically fills to the last row in Excel?

Having trouble setting up an Excel script to autofill a column only down to the final row of data, without extending further. Each table I use this script on has a different number of rows, so hardcoding the row range is not helpful. Is there a way to make ...

Avoiding caching of GET requests in Angular 2 for Internet Explorer 11

My rest endpoint successfully returns a list when calling GET, and I can also use POST to add new items or DELETE to remove them. This functionality is working perfectly in Firefox and Chrome, with the additional note that POST and DELETE also work in IE ...

The FaceDetector within the expo application continues to activate the "onFacesDetected" event in "accurate" mode unnecessarily, even when no face is present

Just starting out with react native and I've been exploring the use of expo FaceDetector for detecting faces. In "fast" mode, the "onFacesDetected" event is triggered correctly. However, when switching to "accurate" mode, the "onFacesDetected" event k ...

Tips for adapting the position of a floating div according to its height and environment

Important Note: The code below utilizes the rubuxa plugin for handling JS sortables. Javascript: function querySelector(expr){return document.querySelector(expr)} var container = querySelector('.ITEST'); var sortable = Sortable.create(container, ...

What is the best way to transmit a two-dimensional array using ajax?

Here is the process I use to send data to the server: var points = []; var coords = polyline.geometry.getCoordinates(); for (var i = 0; i < coords.length; i++) { var x = (coords[i][0]).toFixed(4); var y = (coords[i][1]).toFixed(4); points[i ...

Is it possible to use a Proxy-object instead of just an index when changing tabs in material-ui/Tabs?

Using material-ui tabs, I have a function component called OvertimesReport with Fixed Tabs and Full width tabs panel: const TabContainer = ({children, dir}) => ( <Typography component="div" dir={dir} style={{padding: 8 * 3}}> {children} & ...

Transform the appearance of buttons within AppBar using Material UI React

Embarking on a new project using React and Node JS has led me into the battle with Material UI. My current challenge is customizing the style of AppBar items, particularly the Buttons. Here's what I have in my "Menu" component: const Menu = () => ...

Is there inconsistency in the behavior of json.parse when given the same input?

This query pertains to the differentiation in outputs resulting from various inputs I am not seeking guidance on achieving a specific output. The reason behind the discrepancy in output between two scenarios, despite using the same argument for the JS ...

Trigger a 'change password' notification using Javascript

Issue: I am currently working on developing a web application that includes a password change functionality without the use of form submission. The process I have in mind is as follows: Show a Bootstrap modal pop-up User enters new password Upon clickin ...

Tips for preventing a table from showing up while scrolling unnecessarily when utilizing a heading with the CSS position property set to 'sticky'

Currently, I am facing an issue with creating a sticky header for my table. The problem arises when the header of the table has rounded edges (top right and top left) along with a box-shadow applied to the entire table. As the user scrolls through the tabl ...

Deactivating AngularJS debug information in a gulp / typescript production compilation

What is the most effective approach to disabling debug data in a gulp production build? The recommended method for disabling debug data is: myApp.config(['$compileProvider', function ($compileProvider) { $compileProvider.debugInfoEnabled(false ...

Encountered an error when attempting to submit with Node.js and Express.js connected to MySql - "Cannot POST /login

I am currently working on creating a basic login page using node.js with the express.js and mysql packages. The goal is to redirect users to the layout.html page if their username and password exist in the mysql database. For this project, I have set up a ...

I encounter issues with my fetch request as it is denied while attempting to access the HTML content from the specified

I'm currently working on a project in my express app where I need to retrieve the html code of multiple urls. However, I keep encountering this error: reject(`new FetchError(request to ${request.url}` failed, reason: ${err.message}, 'system' ...