我正在尝试使用我的react-native-ble-manager软件包扫描我的react本机应用程序中的Bluetooth设备。
alert(this.state.ble)
始终返回null。
有些蓝牙设备可用,但是这种方法无法实现 我该怎么办?
代码:
export default class Setting extends React.Component {
constructor(){
super()
this.state = {
ble:null,
scanning:false,
}
}
componentDidMount() {
this.handleDiscoverPeripheral = this.handleDiscoverPeripheral.bind(this);
NativeAppEventEmitter
.addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral );
}
handleScan() {
BleManager.scan([], 30, true)
.then((results) => console.log('Scanning...'));
alert(this.state.ble)
}
toggleScanning(bool){
if (bool) {
this.setState({scanning:true})
this.scanning = setInterval( ()=> this.handleScan(), 3000);
} else{
this.setState({scanning:false, ble: null})
clearInterval(this.scanning);
}
}
handleDiscoverPeripheral(data){
console.log('Got ble data', data);
this.setState({ ble: data })
}
render() {
const container = {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
const bleList = this.state.ble
? <Text> Device found: {this.state.ble.name} </Text>
: <Text>no devices nearby</Text>
return (
<View style={container}>
<TouchableHighlight style={{padding:20, backgroundColor:'#ccc'}} onPress={() => this.toggleScanning(!this.state.scanning) }>
<Text>Scan Bluetooth ({this.state.scanning ? 'on' : 'off'})</Text>
</TouchableHighlight>
{bleList}
</View>
);
}
}