我正在尝试使用BLE连接在Android设备上的react-Native中连接到设备。 我需要使用具有特定名称的设备连接:例如“ deviceName”。 我正在使用react-native-ble-plx。
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
ScrollView,
FlatList,
TextInput,
Platform,
Alert
} from 'react-native';
import { BleManager } from 'react-native-ble-plx';
export default class Main extends Component {
constructor(props) {
super(props);
this.state={
scaning:false,
isConnected:false,
text:'',
writeData:'',
receiveData:'',
readData:'',
bleManager: new BleManager(),
data:[],
isMonitoring:false,
}
this.bluetoothReceiveData = [];
this.deviceMap = new Map();
}
scan() {
if(!this.state.scaning) {
this.setState({scaning:true});
this.deviceMap.clear();
const { bleManager } = this.state;
bleManager.startDeviceScan(null, null, async (error, device) => {
console.log("scanning bluetooth...")
if (device.name === "Proximity") {
bleManager.connectToDevice(device.id, {
autoconnect: true,
timeout: BLUETOOTH_TIMEOUT,
isConnected: true
})
// ............
}
})
}
}
disconnect(){
bleManager.disconnect()
.then(res=>{
this.setState({data:[...this.deviceMap.values()],isConnected:false});
})
.catch(err=>{
this.setState({data:[...this.deviceMap.values()],isConnected:false});
})
}
render(){
return(
<View>
<TouchableOpacity
activeOpacity={0.7}
style={[styles.buttonView,{marginHorizontal:10,height:40,alignItems:'center'}]}
onPress={this.state.isConnected?this.disconnect.bind(this):this.scan.bind(this)}>
<Text style={styles.buttonText}>{this.state.scaning?'Search':this.state.isConnected?'Disconnect Bluetooth':'Search Bluetooth'}</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor:'white',
marginTop:Platform.OS == 'ios'?20:0,
},
item:{
flexDirection:'column',
borderColor:'rgb(235,235,235)',
borderStyle:'solid',
borderBottomWidth:StyleSheet.hairlineWidth,
paddingLeft:10,
paddingVertical:8,
},
buttonView:{
height:30,
backgroundColor:'rgb(33, 150, 243)',
paddingHorizontal:10,
borderRadius:5,
justifyContent:"center",
alignItems:'center',
alignItems:'flex-start',
marginTop:10
},
buttonText:{
color:"white",
fontSize:12,
},
content:{
marginTop:5,
marginBottom:15,
},
textInput:{
paddingLeft:5,
paddingRight:5,
backgroundColor:'white',
height:50,
fontSize:16,
flex:1,
},
})
目前我收到此错误:“未定义不是对象(正在评估'b.default.startDeviceScan')。
如何解决此错误?您认为代码可以直接连接到设备吗?谢谢
答案 0 :(得分:1)
您导出BleManager错误。您必须将其放在这样的括号之间:
import { BleManager } from 'react-native-ble-plx';
您使用BleManager也是错误的。您必须在某个地方实例化它,我习惯在状态下使用它,以确保我只有1个BleManager并像这样创建一个新的BleManager对象:
constructor {
....
this.state = {
....
bleManager: new BleManager(),
....
};
然后使用this.state.bleManager代替您以前使用的BleManager:
const { bleManager } = this.state;
bleManager.startDeviceScan(...)