为什么BleManager.scan方法总是返回null?

时间:2019-09-08 09:01:21

标签: react-native bluetooth-lowenergy react-native-android

我正在尝试使用我的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>
    );
    }
}

0 个答案:

没有答案