ReactNative 蓝牙库,适用于安卓平台
使用npm
$ npm install react-native-bluetooth-android --save
使用 yarn
$ yarn add react-native-bluetooth-android
$ react-native link react-native-bluetooth-android
- 打开
android/app/src/main/java/[...]/MainApplication.java
- 引入
import com.tyanbiao.bluetooth.RNBluetoothPackage;
- 在
list()
方法中添加packages.add(new RNBluetoothPackage());
- 在
android/settings.gradle
文件中加入:include ':react-native-bluetooth-android' project(':react-native-bluetooth-android').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-bluetooth-android/android')
- 在
android/app/build.gradle
的 dependencies 中插入:implementation project(':react-native-bluetooth-android')
git clone https://github.com/tyanbiao/react-native-bluetooth-android.git
cd react-native-bluetooth-android/example
npm i
react-native run-android
全部导入
import * as RNBluetooth from 'react-native-bluetooth-android'
单个导入
import { openBluetoothAdapter } from 'react-native-bluetooth-android'
const res = await openBluetoothAdapter()
const devices = await listDevices()
返回设备列表,类型: Array.<Object>
, devices结构:
{
name: string
address: string
}
startDevicesDiscovery()
stopDevicesDiscovery()
onDeviceFound((device) => {
console.log(device.name)
console.log(device.address)
})
const res = createConnection(address)
closeConnection()
onConnectionLost(() => {
console.log('连接已断开')
})
- 发送二进制数据
const bufferView = new Uint8Array(10)
writeBuffer(bufferView.buffer)
- 发送ascii字符串
const buffer = utils.stringToBuffer('hello world')
writeBuffer(buffer)
- 发送hex字符串
const buffer = utils.hexToBuffer('550d0aeeff')
writeBuffer(buffer)
const handler = (buffer) => {
const bufferView = new Uint8Array(buffer)
// do something
}
onDataReceived(handler)
接收到的数据类型为ArrayBuffer,可以根据实际需求做处理,utils
对象内置了ArrayBuffer转换为ascii和hex编码的方法
import { utils } from 'react-native-bluetooth-android'
let hexStr = utils.bufferToHex(arrayBuffer)
let asciiStr = utils.bufferToString(arrayBuffer)
openBluetoothAdapter
closeBluetoothAdapter
startDevicesDiscovery
stopDevicesDiscovery
listDevices
createConnection
closeConnection
writeBuffer
onDataReceived
onDeviceFound
onConnectionLost
utils
使用async
, await
try {
const res = await openBluetoothAdapter()
console.log(res)
} catch (e) {
console.error(e)
}
使用promise
openBluetoothAdapter().then(result => {
console.log(res)
}).catch(e => {
console.error(e)
})
bufferToString
stringToBuffer
bufferToHex
hexToBuffer