android+ble蓝牙读写,android蓝牙BLE连接流程

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

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值