首先,连接到您的 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;
}}