question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Android not finding bluetooth devices

See original GitHub issue

Version

Tell us which versions you are using:

  • react-native-ble-manager v6.2.8
  • react-native v0.53.0
  • iOS/Android 4.4.2 (Android) - iOS works

Expected behaviour

Should find some devices (tested, iOS finds devices, other Android apps can find devices)

Actual behaviour

Everything works fine, no errors thrown. But no devices are ever found.

Steps to reproduce

Here’s the code of my BluetoothConnector.js class:

import React from 'react'
import BleManager from 'react-native-ble-manager'
import { AppState, NativeEventEmitter, NativeModules } from 'react-native'
import { scanStarted, scanStopped, updatePeripherals, updatePeripheral, newPeripheral } from 'redux/actions'
import store from 'redux/stores'
import _ from 'lodash'

const BleManagerModule = NativeModules.BleManager
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule)

class BluetoothConnector extends React.Component {
	constructor(props){
    super(props)

		BleManager.start({ showAlert: false })

		this.handlerDiscover = bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral)
		this.handlerStop = bleManagerEmitter.addListener('BleManagerStopScan', this.handleStopScan)
		this.handlerDisconnect = bleManagerEmitter.addListener('BleManagerDisconnectPeripheral', this.handleDisconnectedPeripheral)
		this.handlerUpdate = bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', this.handleUpdateValueForCharacteristic)

		AppState.addEventListener('change', this.handleAppStateChange)
	}

	// stopBluetoothManager = () => {
  //   this.handlerDiscover.remove()
  //   this.handlerStop.remove()
  //   this.handlerDisconnect.remove()
  //   this.handlerUpdate.remove()
	// }

	startScan = () => {
	  if(store.getState().ConnectToTrain.scanning == true) return

		console.log('Start scan')

		store.dispatch(updatePeripherals([]))

		BleManager.enableBluetooth()
		  .then(() => {
				BleManager.scan([], 10, true).then((results) => {
			    console.log('Scanning...', results)
					store.dispatch(scanStarted())
			  })
		  })
		  .catch((error) => {
		    // Failure code
		    console.log('The user refused to enable bluetooth');
		  })
	}

	connectToPeripheral = (connectingPeripheral) => {
	  if (!connectingPeripheral) return
	  if(connectingPeripheral.status == 'connected') return

	  let peripherals = store.getState().ConnectToTrain.peripherals
		let peripheral = _.find(peripherals, { id: connectingPeripheral.id })

		peripheral.status = 'connecting'
		store.dispatch(updatePeripheral(peripheral.id, peripheral))

	  BleManager.connect(connectingPeripheral.id).then(() => {
			console.log('Connected to:', peripheral)

			setTimeout(() => {
				BleManager.retrieveServices(connectingPeripheral.id).then((peripheralInfo) => {
					let characteristics = peripheralInfo.characteristics

					peripheral.status = 'connected'
					peripheral.characteristics = characteristics

					store.dispatch(updatePeripheral(peripheral.id, peripheral))

					console.log('store.dispatch peripherals:', peripherals)
					console.log('Retrieved services:', peripheralInfo)
				})
			}, 900)

	  }).catch((error) => {
	    console.log('Error: ', error)
	  })
	}

	sendSignal = (signal) => {
		if(!signal){
			console.log('No signal to be sent. Ending.')
			return
		}
		else {
			console.log('Will try to send signal:', signal)
		}

		let peripherals = store.getState().ConnectToTrain.peripherals
		let connectedPeripheral = _.find(peripherals, { status: 'connected' })

		console.log('Start send to:', connectedPeripheral)

		if(!connectedPeripheral) return

		let notifyCharacteristic = _.find(connectedPeripheral.characteristics, (characteristic) => {
			return characteristic.properties.indexOf('Notify') > -1 && characteristic.characteristic.length > 20
		})
		let writeCharacteristic = _.find(connectedPeripheral.characteristics, (characteristic) => {
			return characteristic.properties.indexOf('Write') > -1 && characteristic.characteristic.length > 20
		})

		console.log('Will try using the writeCharacteristic:', writeCharacteristic, 'Out of:', connectedPeripheral.characteristics)

		BleManager.write(connectedPeripheral.id, writeCharacteristic.service, writeCharacteristic.characteristic, signal)
			.then(() => {
				console.log('Success, wrote:', signal);
			})
			.catch((error) => {
				console.log('Write error:', error);
			})

		// TEMP this a more complex write function with a notification part
		// console.log('Will try using the notifyCharacterstic:', notifyCharacteristic, ', writeCharacteristic:', writeCharacteristic, 'Out of:', connectedPeripheral.characteristics)
	 //    BleManager.startNotification(connectedPeripheral.id, notifyCharacteristic.service, notifyCharacteristic.characteristic).then(() => { // TODO may not need to run startNotification
	 //      console.log('Started notification on:', connectedPeripheral.id)
	 //      setTimeout(() => {
		// 	BleManager.write(connectedPeripheral.id, writeCharacteristic.service, writeCharacteristic.characteristic, signal)
		// 		.then(() => {
		// 	    console.log('Success, wrote:', signal);
		// 	  })
		// 	  .catch((error) => {
		// 	    console.log('Write error:', error);
		// 	  })
	 //      }, 500);
	 //    }).catch((error) => console.log('Notification error:', error))
	}

	retrieveConnected = () => {
	  // let peripherals = store.getState().ConnectToTrain.peripherals
	  BleManager.getConnectedPeripherals([]).then((peripherals) => {
	    // _.forEach(connectedPeripherals, (connectedPeripheral) => {
	    //   let peripheral = _.find(peripherals, { id: connectedPeripheral.id })
	    //   peripheral.status = 'connected'
	    // })
			// store.dispatch(updatePeripherals(peripherals))
			// this.setState({ peripherals: peripherals })
	    console.log('Connected peripherals:', peripherals)
	  })
	}

	disconnectFromPeripheral = (peripheral) => {
	  if(!peripheral) return
	  if(!peripheral.status == 'connected') return
	  BleManager.disconnect(peripheral.id)
	}

	// --------------------------------
	// No need to export the ones below,
	// They are functions of exported functions
	// --------------------------------

	handleAppStateChange = (nextAppState) => {
	  // if (store.getState().ConnectToTrain.appState.match(/inactive|background/) && nextAppState === 'active') {
		// 	this.retrieveConnected()
	  // }
		// store.dispatch(updateAppState(nextAppState))
	}

	handleDisconnectedPeripheral = (data) => {
	  let peripherals = store.getState().ConnectToTrain.peripherals
	  let peripheral = _.find(peripherals, { id: data.peripheral.id })

	  if(!peripheral) return

	  peripheral.status = 'not_connected'

		store.dispatch(updatePeripherals(peripherals))

	  console.log('Disconnected from ' + data.peripheral)
	}

	handleUpdateValueForCharacteristic = (data) => {
	  console.log('Received data from ' + data.peripheral + ' characteristic ' + data.characteristic, data.value);
	}

	handleStopScan = () => {
	  console.log('Scan stopped')
		store.dispatch(scanStopped())

		// Attempting to find peripherals TEMP
		BleManager.getDiscoveredPeripherals([])
		  .then((peripheralsArray) => {
		    // Success code
		    console.log('Discovered peripherals: ' + peripheralsArray.length);
		  })
	}

	handleDiscoverPeripheral = (peripheral) => {
		console.log('Discovered peripheral!', peripheral)
	  let peripherals = store.getState().ConnectToTrain.peripherals
	  if(_.find(peripherals, { id: peripheral.id })) return

	  peripheral.status = 'not_connected'

	  console.log('Discovered peripheral:', peripheral)

		store.dispatch(newPeripheral(peripheral))
	}
}

export default BluetoothConnector

Note: this code has been played around with to attempt to get Android to work, this will probably no longer work on iOS.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
marcosinigagliacommented, Mar 21, 2018

Try to use the forceLegacy flag.

1reaction
astriskitcommented, Mar 21, 2018

Hi. Something similar is happening with my app too. I am able to run my app ( needless to say using react-native-ble-manager ) and find BLE peripherals in these mobiles : Nexus 4 - Android 5.1.1 & one-plus - Android 8, but when I ran the same app in the Samsung Galaxy S6 - Android 7, no peripherals were being discovered. Also I tested the Galaxy with another BLE scanning app from playstore, it was discovering the peripherals, just fine. What could be reason behind this ?? Any ideas ??

Read more comments on GitHub >

github_iconTop Results From Across the Web

Fix Bluetooth problems on Android - Google Support
Step 1: Check Bluetooth basics · Turn Bluetooth off and then on again. Learn how to turn Bluetooth on and off. · Confirm...
Read more >
How to Fix Bluetooth Pairing Problems - Techlicious
1. Make sure Bluetooth is turned on · 2. Determine which pairing process your device employs · 3. Turn on discoverable mode ·...
Read more >
12 Quick Ways to Fix Bluetooth Problems on Android Devices
1. Try to Connect With a Different Device · 2. Turn Off Bluetooth and Then Turn It On Again · 3. Unpair the...
Read more >
How to fix Android Bluetooth not working - Carlcare.com
Open your device Settings. · Tap 'Connected Devices' · Tap 'Bluetooth' · Now select 'Previously connected devices' · Locate your Bluetooth device ...
Read more >
Why Won't My Bluetooth Connect? How to Fix Common Issues
Why won't my Bluetooth device connect?: How to fix common Bluetooth connection issues · How to fix common Bluetooth connection issues · Make...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found