我正在尝试在TI设备与我的应用之间进行BLE通信。目前,不启用配对功能,一切正常,一旦启用配对功能,我就会遇到问题。
1)我的应用要求我提供配对。
2)输入密码
3)APP不起作用
4)我离开APP,返回即可正常运行
5)我从APP重新退出,重新进入无法正常工作,需要配对。
如何解决这些错误?
我在MainActivity中使用它:
private void getpaireddevices(){
Set<BluetoothDevice> devicesArray = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if(devicesArray.size() > 0) {
for(BluetoothDevice device : devicesArray) {
device.getName();
device.getAddress();
}
}
}
这在SelectedDevice中:
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
int prevstate = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
String msg = "Bond state change: state" + pairstate(state) + "previous state" + pairstate(prevstate);
Log.w("Bond state receiver", msg);
}
private String pairstate(int state) {
switch (state) {
case BluetoothDevice.BOND_BONDING:
Log.i("Bondind status:", "Bonding..");
break;
case BluetoothDevice.BOND_BONDED:
Log.i("Bondind status:", "Bonded");
break;
case BluetoothDevice.BOND_NONE:
Log.i("Bondind status:", "Fail");
default:
return String.valueOf(state);
}
return null;
}
};
在扫描设备的主要活动中,我调用createBond ()
,在SelectedDevice中,我调用mBroadcastReceiver4
的寄存器。
答案 0 :(得分:0)
与BLE设备进行交互的第一步是连接到它-更具体地说,是连接到设备上的GATT服务器。
bluetoothGatt = device.connectGatt(context, false, gattCallback);
private final BluetoothGattCallback gattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
connectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
Log.i(TAG, "Attempting to start service discovery:" +
bluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
connectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
} else {
Log.w(TAG, "onConnectionStateChange() status = " + status + " newState = " + newState);
}
}
@Override
// New services discovered
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
}
当您尝试连接到设备时,在onConnectionStateChange()中看到什么日志?
您在设备上发现任何服务吗?
有关连接到BLE设备的更多信息: https://developer.android.com/guide/topics/connectivity/bluetooth-le.html