我正在开发使用设备查找其他设备并通过蓝牙进行连接的功能。
所有源代码都位于TestActivity.java
文件中。
这是Test函数的代码,执行bluetoothDevice.connect(true)
方法来连接另一台设备。
public void functionTest{
.............
BluetoothDevice connDevice;
connDevice.connect(true);
............
}
定义BraodcastReceiver以监视设备连接状态更改状态。 连接后,可以监视更改状态。
private BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
..............
else if(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)){
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
BluetoothAdapter.STATE_DISCONNECTED);
switch(state){
...........
case BluetoothAdapter.STATE_CONNECTED:
...........
}
}
..............
}
有一个问题,当我选择一个设备进行连接时,有时它可以正常工作,有时不起作用。但是设备已显示为[已连接]状态。这意味着BraodcastReceiver
无法始终正确接收连接更改状态。
为什么会这样?我的应用程序中是否有一些错误用法?