蓝牙连接应用程序
我已经编写了扫描设备的服务。
当我通过onLeScan()
回调获取设备时
电话服务添加到列表&监控上次可见的时间并检查某些特征,以及所有现在正在等待用户交互的应用程序。
1)我应该在blutetoothGatt disconnect() or close()?
现在,我打电话给disconnect()
,设备已断开连接,但在再次通话后突然我收到了onLeScan()
回拨
2)我应该对onConnectionStateChange中的连接问题作出反应,还是跳过它并在onLeScan()
回调后接收设备后做一些?
答案 0 :(得分:0)
首先,连接到你的BLE 然后,使用以下代码发现您的服务。
private final BluetoothGattCallback mGattcallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mStatus = newState;
mConnGatt.discoverServices();
Toast.makeText(getApplicationContext(),"Device Connected", Toast.LENGTH_SHORT).show();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mStatus = newState;
runOnUiThread(new Runnable() {
public void run() {
setInterval.setEnabled(false);
}
});
}
}
在callBack之后,将UUID设置为按钮。我正在使用setInterval按钮。
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
for (BluetoothGattService service : gatt.getServices()) {
if ((service == null) || (service.getUuid() == null)) {
continue;
}
if (BleUuid.IR_SERVICE.equalsIgnoreCase(service
.getUuid().toString())) {
runOnUiThread(new Runnable() {
public void run() {
setInterval.setEnabled(true);
}
});
setInterval.setTag(service
.getCharacteristic(UUID
.fromString(BleUuid.WRITE_TIME)));
}
runOnUiThread(new Runnable() {
public void run() {
setProgressBarIndeterminateVisibility(false);
}
});
}}
然后,读写类
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
if (BleUuid.CHAR_MANUFACTURER_NAME_STRING
.equalsIgnoreCase(characteristic.getUuid().toString())) {
final String name = characteristic.getStringValue(0);
runOnUiThread(new Runnable() {
public void run() {
setInterval.setText(name);
setProgressBarIndeterminateVisibility(false);
}
});
}
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
runOnUiThread(new Runnable() {
public void run() {
setProgressBarIndeterminateVisibility(false);
}
});
}
};
然后我使用了一个点击监听器将数据发送到BLE。
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.setinterval:
if ((v.getTag() != null)
&& (v.getTag() instanceof BluetoothGattCharacteristic)) {
BluetoothGattCharacteristic ch = (BluetoothGattCharacteristic) v
.getTag();
String hr = String.valueOf(tp.getCurrentHour());
String min = String.valueOf(tp.getCurrentMinute());
String interval = new StringBuilder().append(hr).append(min).toString();
ch.setValue(interval);
if (mConnGatt.writeCharacteristic(ch)) {
setProgressBarIndeterminateVisibility(true);
Toast.makeText(getApplicationContext(),R.string.toast_interval +interval, Toast.LENGTH_SHORT).show();
}
}
break;
}}