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

Utilize JSON data to display markers on Leaflet maps

I am exploring the world of Leaflet and I have a question about loading markers from a database into a leaflet map using PHP. In my PHP code, I extract latitude and longitude data from the database based on the selected ward and encode it in JSON format. ...

Soft keyboard on mobile fails to update when arrows are used in Ajax-populated dropdown menus

I am working on a web form that includes two select fields: Country and City: <select id="country" onchange="getCity(this);"> <option value="">-- Please select your country --</option> <option value="1">Austria& ...

Toggle the visibility of multiple divs by clicking on other divs

I have implemented a script on my webpage to toggle the visibility of certain divs by clicking on anchor tags. I found a solution that seems perfect for my needs, but unfortunately it is not working when I try to integrate it into my own website. I suspec ...

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

Utilizing iOS Local Storage for Efficient Form Submission Handling

I feel like my brain is on the verge of exploding. I just can't seem to get this to work as intended, and I'm struggling to pinpoint the issue. Currently, I have a form that needs to be processed using AJAX. Before proceeding with that, I want ...

The function os.platform in React and Electron mistakenly identifies the browser as the operating system instead of the actual OS

In my quest to locate the appdata folder for the application, I encountered a challenge where each operating system has a different path for the appdata or application support folder. To address this, I attempted to identify the OS type in order to deter ...

Conceal the Addon Tab across all pages in Storybook

Is there a way to globally hide an Addon Tab without disabling the addon itself? Specifically, I am using version 5.3.18 of Storybook with React and I want to hide the tab panel from the addon "styled-component theme". I apologize for the basic question, ...

Trouble arises with Javascript object destructuring when used with this.props in React

Just recently I discovered object destructuring with a basic object, which worked perfectly. However, when attempting to apply it in React on this.props, all my variables are returning as undefined. I'm unsure of what mistake I might be making here. A ...

Ways to detect the use of vue.js on a webpage without relying on vue-devtools

One way to determine if the page is utilizing Angular or AngularJS is by inspecting window.ng and window.angular. Is there a similar method to identify whether Vue is being used on the page directly from the console, without relying on vue-devtools? ...

Using the HTML form element to achieve two-way binding on array elements

I am working with an array of objects within a component that will be iterated in the template. app.component.ts import {Component, OnInit} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.compone ...

JavaScript code that loads a copied mesh object using three.js

Currently using three.js version r59, encountering difficulties when attempting to duplicate a loaded model. The goal is to create multiple models through looping, with the plan to apply textures at a later stage. for (var i=0; i<5-1; i++){ va ...

Fetching data from a database for Vue.js using the Summernote editor

I previously inquired about integrating summernote with vue.js and received a helpful response here. It worked seamlessly with v-model binding. However, I encountered an issue when attempting to load data from the database for an edit page. The data was n ...

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

As soon as I inserted the image, the text vanished into thin air

The phrase "welcome" is not displaying after I included the av tag <!DOCTYPE html> <html> <style> @font-face { font-family: OpenSans; src: url(OpenSans-Bold.ttf); } * { ...

The browser has surpassed the maximum call stack size while trying to refresh with socket.io, causing an error

I've encountered an issue with my Node js server crashing whenever I refresh the browser. The websocket connection works fine initially, but upon refreshing, the server crashes with the following error: E:\Back\node_modules\socket.io-pa ...

Exploring the meaning behind RxJS debounce principles

Referencing information found in this source: const debouncedInput = example.debounceTime(5); const subscribe = debouncedInput.subscribe(val => { console.log(`Debounced Input: ${val}`); }); When the first keyup event occurs, will the debouncedI ...

Determining the best time to utilize AngularJS data binding compared to Rails data binding depends on the

Combining Rails and AngularJS appears to be a promising combination. However, I find myself struggling with the concept of data binding. In AngularJS, data is provided through a scope which then generates content based on that data. On the other hand, my ...

Can you provide guidance on how to pass the selected value from a select option to an onchange function using Vue.js methods?

I'm facing an issue with passing the selected option value id from a select option to an onchange function in my methods. My goal is to store the selected value in the v-model "choosed" every time the user changes the select option, and then pass that ...

Site performance stalls when a trailing slash is present in the URL while using Express routing

Whenever I visit a page on my development site with a URL like localhost:8000/news, everything loads perfectly fine. However, if I add a trailing slash to the URL, such as localhost:8000/news/, the entire site freezes. It seems to be trying to load partial ...

Vue fails to reflect changes in data when it is updated

I have a page where I can access data by calling domain.com/subpage?soundfile=something Using the fetch method, I extract the query parameter from the URL to retrieve the necessary information. The retrieval process is successful as indicated by the data ...