问题描述:在使用BLE(蓝牙低功耗)时,无法在BluetoothGattCallback的onConnectionStateChange方法中更改视图。
解决方法:
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if(newState == BluetoothProfile.STATE_CONNECTED) {
// 连接成功
// 在这里进行视图的更改
} else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
// 连接断开
// 在这里进行视图的更改
}
}
};
使用Handler的示例代码:
private Handler mHandler = new Handler(Looper.getMainLooper());
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
mHandler.post(new Runnable() {
@Override
public void run() {
if(newState == BluetoothProfile.STATE_CONNECTED) {
// 连接成功
// 在这里进行视图的更改
} else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
// 连接断开
// 在这里进行视图的更改
}
}
});
}
};
使用runOnUiThread的示例代码:
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
runOnUiThread(new Runnable() {
@Override
public void run() {
if(newState == BluetoothProfile.STATE_CONNECTED) {
// 连接成功
// 在这里进行视图的更改
} else if(newState == BluetoothProfile.STATE_DISCONNECTED) {
// 连接断开
// 在这里进行视图的更改
}
}
});
}
};
通过以上的解决方法,你应该能够在BluetoothGattCallback的onConnectionStateChange方法中成功更改视图。