上代码:
//当有客户端来写Descriptor时回调的接口
@Override
public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onDescriptorWriteRequest -----%%%%%%%%% "+device.getName());
notify.setValue("测试啊数据".getBytes());
devices = device;
// bluetoothGattServer.sendResponse(device,requestId, BluetoothGatt.GATT_SUCCESS,offset,notify.getValue());
// bluetoothGattServer.notifyCharacteristicChanged(device,notify,true);
handler.sendEmptyMessage(1);
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
super.onExecuteWrite(device, requestId, execute);
}
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
devices = device;
long t = System.currentTimeMillis() - time;
Log.e("fange","onNotificationSent -----%%%%%%%%% "+t+" "+status);
if (t < 1000){
handler.postDelayed(runnable,1000-t);
}else {
Message msg = new Message();
msg.what = 1 ;
msg.obj = device;
handler.sendMessage(msg);
}
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
handler.removeCallbacks(runnable);
Object o = msg.obj;
BluetoothGattCharacteristic notify = bluetoothGattServer.getService(UUID.fromString(serviceuuidString)).getCharacteristic(UUID.fromString(notifyuuid));
notify.setValue(("测试数据"+(code)).getBytes());
notify.getDescriptor(UUID.fromString(ssddd)).setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
Log.w("wyj",o+" server = "+bluetoothGattServer+" notify = "+notify+" devices = "+devices+" value = "+(notify == null?"-1":new String(notify.getValue()))+" size = "+(notify == null?-1:notify.getValue().length)
+" notify id = "+notify.getInstanceId()
);
if (bluetoothGattServer != null && notify != null) {
if (o != null || (o instanceof BluetoothDevice))
bluetoothGattServer.notifyCharacteristicChanged((BluetoothDevice)o, notify, false);
else
bluetoothGattServer.notifyCharacteristicChanged(devices, notify, false);
}
code ++ ;
time = System.currentTimeMillis();
// handler.postDelayed(runnable,1000);
break;
}
}
};
球大神指导这是为啥。
4 个解决方案
#1
所有代码如下:
public class MyBleTest extends BaseBleActivity{
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeAdvertiser advertiser;
private AdvertiseSettings advertiseSettings = null;
private String serviceuuidString = "0000fee9-0000-1000-8000-00805f9b34fb",
notifyuuid = "d44bc439-abfd-45a2-b575-925416129601",
readuuidString = "0d44bc439-abfd-45a2-b575-925416129600",
writeuuidString = "d44bc439-abfd-45a2-b575-925416129600",
ssddd = "00002902-0000-1000-8000-00805f9b34fb";
private BluetoothGattServer bluetoothGattServer;
private BluetoothGattCharacteristic read,write,notify;
private BluetoothGattService service ;
private BluetoothGattDescriptor defs;
private int code = 100 ;
private BluetoothDevice devices ;
private long time = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sss);
init();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void init(){
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
showToast("设备不支持ble111");
return;
}
bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
if (bluetoothManager != null)
bluetoothAdapter = bluetoothManager.getAdapter();
else {
showToast("设备不支持ble11122");
return;
}
if (bluetoothAdapter == null){
showToast("设备不支持ble333");
return;
}
if (!bluetoothAdapter.isEnabled())
bluetoothAdapter.enable();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
}
// if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
// bluetoothAdapter.enable();
//
// } else {
// showToast("设备不支持ble333");
// return;
// }
if (advertiser == null){
showToast("设备不支持ble444");
return;
}
initAdvertise();
}
/**设置广播参数*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initAdvertise(){
AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();
builder.setConnectable(true);
builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);//设置广播的模式,应该是跟功耗相关
builder.setTimeout(100);
builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
advertiseSettings = builder.build();
//广播参数
AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
bluetoothAdapter.setName("my Test Ble"); //你想叫啥名字,你愿意就好
dataBuilder.setIncludeDeviceName(true);
dataBuilder.setIncludeTxPowerLevel(true);
dataBuilder.addServiceUuid(ParcelUuid.fromString(serviceuuidString)); //可自定义UUID,看看官方有没有定义哦
AdvertiseData data = dataBuilder.build();
bluetoothGattServer = bluetoothManager.openGattServer(MyBleTest.this,bluetoothGattServerCallback);
if (bluetoothGattServer == null)
Log.e("fange"," gatt server is null");
else {
addBleServices();
advertiser.startAdvertising(advertiseSettings, data, advertiseCallback);
}
}
private AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
if (settingsInEffect == null){
Log.e("fange","蓝牙广播 -- settingsInEffect 是空的");
}else {
Log.e("fange","蓝牙广播,有数据 "+settingsInEffect.toString());
}
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
Log.e("fange","蓝牙广播开启错误....错误代码 "+ errorCode);
}
};
private void addBleServices(){
service = new BluetoothGattService(UUID.fromString(serviceuuidString),BluetoothGattService.SERVICE_TYPE_PRIMARY);
read = new BluetoothGattCharacteristic(UUID.fromString(readuuidString),BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PROPERTY_WRITE);
notify = new BluetoothGattCharacteristic(UUID.fromString(notifyuuid),BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PROPERTY_WRITE);
defs = new BluetoothGattDescriptor(UUID.fromString(ssddd),BluetoothGattDescriptor.PERMISSION_READ|BluetoothGattDescriptor.PERMISSION_WRITE);
read.setValue("666".getBytes());
notify.setValue("fange".getBytes());
defs.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
notify.addDescriptor(defs);
service.addCharacteristic(read);
service.addCharacteristic(notify);
// service.addCharacteristic(def);
service.addService(service);
bluetoothGattServer.addService(service);
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
handler.removeCallbacks(runnable);
Object o = msg.obj;
BluetoothGattCharacteristic notify = bluetoothGattServer.getService(UUID.fromString(serviceuuidString)).getCharacteristic(UUID.fromString(notifyuuid));
notify.setValue(("测试数据"+(code)).getBytes());
notify.getDescriptor(UUID.fromString(ssddd)).setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
Log.w("wyj",o+" server = "+bluetoothGattServer+" notify = "+notify+" devices = "+devices+" value = "+(notify == null?"-1":new String(notify.getValue()))+" size = "+(notify == null?-1:notify.getValue().length)
+" notify id = "+notify.getInstanceId()
);
if (bluetoothGattServer != null && notify != null) {
if (o != null || (o instanceof BluetoothDevice))
bluetoothGattServer.notifyCharacteristicChanged((BluetoothDevice)o, notify, false);
else
bluetoothGattServer.notifyCharacteristicChanged(devices, notify, false);
}
code ++ ;
time = System.currentTimeMillis();
// handler.postDelayed(runnable,1000);
break;
}
}
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
};
public class MyBleTest extends BaseBleActivity{
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeAdvertiser advertiser;
private AdvertiseSettings advertiseSettings = null;
private String serviceuuidString = "0000fee9-0000-1000-8000-00805f9b34fb",
notifyuuid = "d44bc439-abfd-45a2-b575-925416129601",
readuuidString = "0d44bc439-abfd-45a2-b575-925416129600",
writeuuidString = "d44bc439-abfd-45a2-b575-925416129600",
ssddd = "00002902-0000-1000-8000-00805f9b34fb";
private BluetoothGattServer bluetoothGattServer;
private BluetoothGattCharacteristic read,write,notify;
private BluetoothGattService service ;
private BluetoothGattDescriptor defs;
private int code = 100 ;
private BluetoothDevice devices ;
private long time = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sss);
init();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void init(){
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
showToast("设备不支持ble111");
return;
}
bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
if (bluetoothManager != null)
bluetoothAdapter = bluetoothManager.getAdapter();
else {
showToast("设备不支持ble11122");
return;
}
if (bluetoothAdapter == null){
showToast("设备不支持ble333");
return;
}
if (!bluetoothAdapter.isEnabled())
bluetoothAdapter.enable();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
}
// if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
// bluetoothAdapter.enable();
//
// } else {
// showToast("设备不支持ble333");
// return;
// }
if (advertiser == null){
showToast("设备不支持ble444");
return;
}
initAdvertise();
}
/**设置广播参数*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initAdvertise(){
AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();
builder.setConnectable(true);
builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);//设置广播的模式,应该是跟功耗相关
builder.setTimeout(100);
builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
advertiseSettings = builder.build();
//广播参数
AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
bluetoothAdapter.setName("my Test Ble"); //你想叫啥名字,你愿意就好
dataBuilder.setIncludeDeviceName(true);
dataBuilder.setIncludeTxPowerLevel(true);
dataBuilder.addServiceUuid(ParcelUuid.fromString(serviceuuidString)); //可自定义UUID,看看官方有没有定义哦
AdvertiseData data = dataBuilder.build();
bluetoothGattServer = bluetoothManager.openGattServer(MyBleTest.this,bluetoothGattServerCallback);
if (bluetoothGattServer == null)
Log.e("fange"," gatt server is null");
else {
addBleServices();
advertiser.startAdvertising(advertiseSettings, data, advertiseCallback);
}
}
private AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
if (settingsInEffect == null){
Log.e("fange","蓝牙广播 -- settingsInEffect 是空的");
}else {
Log.e("fange","蓝牙广播,有数据 "+settingsInEffect.toString());
}
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
Log.e("fange","蓝牙广播开启错误....错误代码 "+ errorCode);
}
};
private void addBleServices(){
service = new BluetoothGattService(UUID.fromString(serviceuuidString),BluetoothGattService.SERVICE_TYPE_PRIMARY);
read = new BluetoothGattCharacteristic(UUID.fromString(readuuidString),BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PROPERTY_WRITE);
notify = new BluetoothGattCharacteristic(UUID.fromString(notifyuuid),BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PROPERTY_WRITE);
defs = new BluetoothGattDescriptor(UUID.fromString(ssddd),BluetoothGattDescriptor.PERMISSION_READ|BluetoothGattDescriptor.PERMISSION_WRITE);
read.setValue("666".getBytes());
notify.setValue("fange".getBytes());
defs.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
notify.addDescriptor(defs);
service.addCharacteristic(read);
service.addCharacteristic(notify);
// service.addCharacteristic(def);
service.addService(service);
bluetoothGattServer.addService(service);
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
handler.removeCallbacks(runnable);
Object o = msg.obj;
BluetoothGattCharacteristic notify = bluetoothGattServer.getService(UUID.fromString(serviceuuidString)).getCharacteristic(UUID.fromString(notifyuuid));
notify.setValue(("测试数据"+(code)).getBytes());
notify.getDescriptor(UUID.fromString(ssddd)).setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
Log.w("wyj",o+" server = "+bluetoothGattServer+" notify = "+notify+" devices = "+devices+" value = "+(notify == null?"-1":new String(notify.getValue()))+" size = "+(notify == null?-1:notify.getValue().length)
+" notify id = "+notify.getInstanceId()
);
if (bluetoothGattServer != null && notify != null) {
if (o != null || (o instanceof BluetoothDevice))
bluetoothGattServer.notifyCharacteristicChanged((BluetoothDevice)o, notify, false);
else
bluetoothGattServer.notifyCharacteristicChanged(devices, notify, false);
}
code ++ ;
time = System.currentTimeMillis();
// handler.postDelayed(runnable,1000);
break;
}
}
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
};
#2
private BluetoothGattServerCallback bluetoothGattServerCallback = new BluetoothGattServerCallback() {
//BLE连接状态改变后回调的接口
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
Log.e("fange","onConnectionStateChange -----%%%%%%%%% ");
}
//当添加一个GattService成功后会回调改接口。
@Override
public void onServiceAdded(int status, BluetoothGattService service) {
super.onServiceAdded(status, service);
Log.e("fange","onServiceAdded -----%%%%%%%%% ");
}
//当有客户端来读数据时回调的接口
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
Log.e("fange","onCharacteristicReadRequest -----%%%%%%%%% ");
}
//当有客户端来写数据时回调的接口
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onCharacteristicWriteRequest -----%%%%%%%%% "+ new String(characteristic.getValue()));
bluetoothGattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,offset,"success".getBytes());
}
@Override
public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
Log.e("fange","onDescriptorReadRequest -----%%%%%%%%% ");
bluetoothGattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,offset,"read success".getBytes());
}
//当有客户端来写Descriptor时回调的接口
@Override
public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onDescriptorWriteRequest -----%%%%%%%%% "+device.getName());
notify.setValue("测试啊数据".getBytes());
devices = device;
// bluetoothGattServer.sendResponse(device,requestId, BluetoothGatt.GATT_SUCCESS,offset,notify.getValue());
// bluetoothGattServer.notifyCharacteristicChanged(device,notify,true);
handler.sendEmptyMessage(1);
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
super.onExecuteWrite(device, requestId, execute);
}
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
devices = device;
long t = System.currentTimeMillis() - time;
Log.e("fange","onNotificationSent -----%%%%%%%%% "+t+" "+status);
if (t < 1000){
handler.postDelayed(runnable,1000-t);
}else {
Message msg = new Message();
msg.what = 1 ;
msg.obj = device;
handler.sendMessage(msg);
}
}
@Override
public void onMtuChanged(BluetoothDevice device, int mtu) {
super.onMtuChanged(device, mtu);
}
};
//BLE连接状态改变后回调的接口
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
Log.e("fange","onConnectionStateChange -----%%%%%%%%% ");
}
//当添加一个GattService成功后会回调改接口。
@Override
public void onServiceAdded(int status, BluetoothGattService service) {
super.onServiceAdded(status, service);
Log.e("fange","onServiceAdded -----%%%%%%%%% ");
}
//当有客户端来读数据时回调的接口
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
Log.e("fange","onCharacteristicReadRequest -----%%%%%%%%% ");
}
//当有客户端来写数据时回调的接口
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onCharacteristicWriteRequest -----%%%%%%%%% "+ new String(characteristic.getValue()));
bluetoothGattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,offset,"success".getBytes());
}
@Override
public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
Log.e("fange","onDescriptorReadRequest -----%%%%%%%%% ");
bluetoothGattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,offset,"read success".getBytes());
}
//当有客户端来写Descriptor时回调的接口
@Override
public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onDescriptorWriteRequest -----%%%%%%%%% "+device.getName());
notify.setValue("测试啊数据".getBytes());
devices = device;
// bluetoothGattServer.sendResponse(device,requestId, BluetoothGatt.GATT_SUCCESS,offset,notify.getValue());
// bluetoothGattServer.notifyCharacteristicChanged(device,notify,true);
handler.sendEmptyMessage(1);
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
super.onExecuteWrite(device, requestId, execute);
}
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
devices = device;
long t = System.currentTimeMillis() - time;
Log.e("fange","onNotificationSent -----%%%%%%%%% "+t+" "+status);
if (t < 1000){
handler.postDelayed(runnable,1000-t);
}else {
Message msg = new Message();
msg.what = 1 ;
msg.obj = device;
handler.sendMessage(msg);
}
}
@Override
public void onMtuChanged(BluetoothDevice device, int mtu) {
super.onMtuChanged(device, mtu);
}
};
#3
问题知道了,原因是app连接异常断开,但是发通知模块未做处理导致
#4
使用notifyCharacteristicChanged,未进入onNotificationSent的回调,楼主可否告知原因,万分感激。
#1
所有代码如下:
public class MyBleTest extends BaseBleActivity{
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeAdvertiser advertiser;
private AdvertiseSettings advertiseSettings = null;
private String serviceuuidString = "0000fee9-0000-1000-8000-00805f9b34fb",
notifyuuid = "d44bc439-abfd-45a2-b575-925416129601",
readuuidString = "0d44bc439-abfd-45a2-b575-925416129600",
writeuuidString = "d44bc439-abfd-45a2-b575-925416129600",
ssddd = "00002902-0000-1000-8000-00805f9b34fb";
private BluetoothGattServer bluetoothGattServer;
private BluetoothGattCharacteristic read,write,notify;
private BluetoothGattService service ;
private BluetoothGattDescriptor defs;
private int code = 100 ;
private BluetoothDevice devices ;
private long time = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sss);
init();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void init(){
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
showToast("设备不支持ble111");
return;
}
bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
if (bluetoothManager != null)
bluetoothAdapter = bluetoothManager.getAdapter();
else {
showToast("设备不支持ble11122");
return;
}
if (bluetoothAdapter == null){
showToast("设备不支持ble333");
return;
}
if (!bluetoothAdapter.isEnabled())
bluetoothAdapter.enable();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
}
// if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
// bluetoothAdapter.enable();
//
// } else {
// showToast("设备不支持ble333");
// return;
// }
if (advertiser == null){
showToast("设备不支持ble444");
return;
}
initAdvertise();
}
/**设置广播参数*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initAdvertise(){
AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();
builder.setConnectable(true);
builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);//设置广播的模式,应该是跟功耗相关
builder.setTimeout(100);
builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
advertiseSettings = builder.build();
//广播参数
AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
bluetoothAdapter.setName("my Test Ble"); //你想叫啥名字,你愿意就好
dataBuilder.setIncludeDeviceName(true);
dataBuilder.setIncludeTxPowerLevel(true);
dataBuilder.addServiceUuid(ParcelUuid.fromString(serviceuuidString)); //可自定义UUID,看看官方有没有定义哦
AdvertiseData data = dataBuilder.build();
bluetoothGattServer = bluetoothManager.openGattServer(MyBleTest.this,bluetoothGattServerCallback);
if (bluetoothGattServer == null)
Log.e("fange"," gatt server is null");
else {
addBleServices();
advertiser.startAdvertising(advertiseSettings, data, advertiseCallback);
}
}
private AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
if (settingsInEffect == null){
Log.e("fange","蓝牙广播 -- settingsInEffect 是空的");
}else {
Log.e("fange","蓝牙广播,有数据 "+settingsInEffect.toString());
}
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
Log.e("fange","蓝牙广播开启错误....错误代码 "+ errorCode);
}
};
private void addBleServices(){
service = new BluetoothGattService(UUID.fromString(serviceuuidString),BluetoothGattService.SERVICE_TYPE_PRIMARY);
read = new BluetoothGattCharacteristic(UUID.fromString(readuuidString),BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PROPERTY_WRITE);
notify = new BluetoothGattCharacteristic(UUID.fromString(notifyuuid),BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PROPERTY_WRITE);
defs = new BluetoothGattDescriptor(UUID.fromString(ssddd),BluetoothGattDescriptor.PERMISSION_READ|BluetoothGattDescriptor.PERMISSION_WRITE);
read.setValue("666".getBytes());
notify.setValue("fange".getBytes());
defs.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
notify.addDescriptor(defs);
service.addCharacteristic(read);
service.addCharacteristic(notify);
// service.addCharacteristic(def);
service.addService(service);
bluetoothGattServer.addService(service);
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
handler.removeCallbacks(runnable);
Object o = msg.obj;
BluetoothGattCharacteristic notify = bluetoothGattServer.getService(UUID.fromString(serviceuuidString)).getCharacteristic(UUID.fromString(notifyuuid));
notify.setValue(("测试数据"+(code)).getBytes());
notify.getDescriptor(UUID.fromString(ssddd)).setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
Log.w("wyj",o+" server = "+bluetoothGattServer+" notify = "+notify+" devices = "+devices+" value = "+(notify == null?"-1":new String(notify.getValue()))+" size = "+(notify == null?-1:notify.getValue().length)
+" notify id = "+notify.getInstanceId()
);
if (bluetoothGattServer != null && notify != null) {
if (o != null || (o instanceof BluetoothDevice))
bluetoothGattServer.notifyCharacteristicChanged((BluetoothDevice)o, notify, false);
else
bluetoothGattServer.notifyCharacteristicChanged(devices, notify, false);
}
code ++ ;
time = System.currentTimeMillis();
// handler.postDelayed(runnable,1000);
break;
}
}
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
};
public class MyBleTest extends BaseBleActivity{
private BluetoothManager bluetoothManager;
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeAdvertiser advertiser;
private AdvertiseSettings advertiseSettings = null;
private String serviceuuidString = "0000fee9-0000-1000-8000-00805f9b34fb",
notifyuuid = "d44bc439-abfd-45a2-b575-925416129601",
readuuidString = "0d44bc439-abfd-45a2-b575-925416129600",
writeuuidString = "d44bc439-abfd-45a2-b575-925416129600",
ssddd = "00002902-0000-1000-8000-00805f9b34fb";
private BluetoothGattServer bluetoothGattServer;
private BluetoothGattCharacteristic read,write,notify;
private BluetoothGattService service ;
private BluetoothGattDescriptor defs;
private int code = 100 ;
private BluetoothDevice devices ;
private long time = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sss);
init();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void init(){
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
showToast("设备不支持ble111");
return;
}
bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
if (bluetoothManager != null)
bluetoothAdapter = bluetoothManager.getAdapter();
else {
showToast("设备不支持ble11122");
return;
}
if (bluetoothAdapter == null){
showToast("设备不支持ble333");
return;
}
if (!bluetoothAdapter.isEnabled())
bluetoothAdapter.enable();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
advertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
}
// if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
// bluetoothAdapter.enable();
//
// } else {
// showToast("设备不支持ble333");
// return;
// }
if (advertiser == null){
showToast("设备不支持ble444");
return;
}
initAdvertise();
}
/**设置广播参数*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void initAdvertise(){
AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();
builder.setConnectable(true);
builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);//设置广播的模式,应该是跟功耗相关
builder.setTimeout(100);
builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
advertiseSettings = builder.build();
//广播参数
AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
bluetoothAdapter.setName("my Test Ble"); //你想叫啥名字,你愿意就好
dataBuilder.setIncludeDeviceName(true);
dataBuilder.setIncludeTxPowerLevel(true);
dataBuilder.addServiceUuid(ParcelUuid.fromString(serviceuuidString)); //可自定义UUID,看看官方有没有定义哦
AdvertiseData data = dataBuilder.build();
bluetoothGattServer = bluetoothManager.openGattServer(MyBleTest.this,bluetoothGattServerCallback);
if (bluetoothGattServer == null)
Log.e("fange"," gatt server is null");
else {
addBleServices();
advertiser.startAdvertising(advertiseSettings, data, advertiseCallback);
}
}
private AdvertiseCallback advertiseCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
if (settingsInEffect == null){
Log.e("fange","蓝牙广播 -- settingsInEffect 是空的");
}else {
Log.e("fange","蓝牙广播,有数据 "+settingsInEffect.toString());
}
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
Log.e("fange","蓝牙广播开启错误....错误代码 "+ errorCode);
}
};
private void addBleServices(){
service = new BluetoothGattService(UUID.fromString(serviceuuidString),BluetoothGattService.SERVICE_TYPE_PRIMARY);
read = new BluetoothGattCharacteristic(UUID.fromString(readuuidString),BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PROPERTY_WRITE);
notify = new BluetoothGattCharacteristic(UUID.fromString(notifyuuid),BluetoothGattCharacteristic.PROPERTY_READ|BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY,
BluetoothGattCharacteristic.PERMISSION_READ|BluetoothGattCharacteristic.PROPERTY_WRITE);
defs = new BluetoothGattDescriptor(UUID.fromString(ssddd),BluetoothGattDescriptor.PERMISSION_READ|BluetoothGattDescriptor.PERMISSION_WRITE);
read.setValue("666".getBytes());
notify.setValue("fange".getBytes());
defs.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
notify.addDescriptor(defs);
service.addCharacteristic(read);
service.addCharacteristic(notify);
// service.addCharacteristic(def);
service.addService(service);
bluetoothGattServer.addService(service);
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
handler.removeCallbacks(runnable);
Object o = msg.obj;
BluetoothGattCharacteristic notify = bluetoothGattServer.getService(UUID.fromString(serviceuuidString)).getCharacteristic(UUID.fromString(notifyuuid));
notify.setValue(("测试数据"+(code)).getBytes());
notify.getDescriptor(UUID.fromString(ssddd)).setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
Log.w("wyj",o+" server = "+bluetoothGattServer+" notify = "+notify+" devices = "+devices+" value = "+(notify == null?"-1":new String(notify.getValue()))+" size = "+(notify == null?-1:notify.getValue().length)
+" notify id = "+notify.getInstanceId()
);
if (bluetoothGattServer != null && notify != null) {
if (o != null || (o instanceof BluetoothDevice))
bluetoothGattServer.notifyCharacteristicChanged((BluetoothDevice)o, notify, false);
else
bluetoothGattServer.notifyCharacteristicChanged(devices, notify, false);
}
code ++ ;
time = System.currentTimeMillis();
// handler.postDelayed(runnable,1000);
break;
}
}
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
};
#2
private BluetoothGattServerCallback bluetoothGattServerCallback = new BluetoothGattServerCallback() {
//BLE连接状态改变后回调的接口
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
Log.e("fange","onConnectionStateChange -----%%%%%%%%% ");
}
//当添加一个GattService成功后会回调改接口。
@Override
public void onServiceAdded(int status, BluetoothGattService service) {
super.onServiceAdded(status, service);
Log.e("fange","onServiceAdded -----%%%%%%%%% ");
}
//当有客户端来读数据时回调的接口
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
Log.e("fange","onCharacteristicReadRequest -----%%%%%%%%% ");
}
//当有客户端来写数据时回调的接口
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onCharacteristicWriteRequest -----%%%%%%%%% "+ new String(characteristic.getValue()));
bluetoothGattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,offset,"success".getBytes());
}
@Override
public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
Log.e("fange","onDescriptorReadRequest -----%%%%%%%%% ");
bluetoothGattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,offset,"read success".getBytes());
}
//当有客户端来写Descriptor时回调的接口
@Override
public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onDescriptorWriteRequest -----%%%%%%%%% "+device.getName());
notify.setValue("测试啊数据".getBytes());
devices = device;
// bluetoothGattServer.sendResponse(device,requestId, BluetoothGatt.GATT_SUCCESS,offset,notify.getValue());
// bluetoothGattServer.notifyCharacteristicChanged(device,notify,true);
handler.sendEmptyMessage(1);
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
super.onExecuteWrite(device, requestId, execute);
}
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
devices = device;
long t = System.currentTimeMillis() - time;
Log.e("fange","onNotificationSent -----%%%%%%%%% "+t+" "+status);
if (t < 1000){
handler.postDelayed(runnable,1000-t);
}else {
Message msg = new Message();
msg.what = 1 ;
msg.obj = device;
handler.sendMessage(msg);
}
}
@Override
public void onMtuChanged(BluetoothDevice device, int mtu) {
super.onMtuChanged(device, mtu);
}
};
//BLE连接状态改变后回调的接口
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
Log.e("fange","onConnectionStateChange -----%%%%%%%%% ");
}
//当添加一个GattService成功后会回调改接口。
@Override
public void onServiceAdded(int status, BluetoothGattService service) {
super.onServiceAdded(status, service);
Log.e("fange","onServiceAdded -----%%%%%%%%% ");
}
//当有客户端来读数据时回调的接口
@Override
public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
Log.e("fange","onCharacteristicReadRequest -----%%%%%%%%% ");
}
//当有客户端来写数据时回调的接口
@Override
public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onCharacteristicWriteRequest -----%%%%%%%%% "+ new String(characteristic.getValue()));
bluetoothGattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,offset,"success".getBytes());
}
@Override
public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
Log.e("fange","onDescriptorReadRequest -----%%%%%%%%% ");
bluetoothGattServer.sendResponse(device,requestId,BluetoothGatt.GATT_SUCCESS,offset,"read success".getBytes());
}
//当有客户端来写Descriptor时回调的接口
@Override
public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
Log.e("fange","onDescriptorWriteRequest -----%%%%%%%%% "+device.getName());
notify.setValue("测试啊数据".getBytes());
devices = device;
// bluetoothGattServer.sendResponse(device,requestId, BluetoothGatt.GATT_SUCCESS,offset,notify.getValue());
// bluetoothGattServer.notifyCharacteristicChanged(device,notify,true);
handler.sendEmptyMessage(1);
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {
super.onExecuteWrite(device, requestId, execute);
}
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
devices = device;
long t = System.currentTimeMillis() - time;
Log.e("fange","onNotificationSent -----%%%%%%%%% "+t+" "+status);
if (t < 1000){
handler.postDelayed(runnable,1000-t);
}else {
Message msg = new Message();
msg.what = 1 ;
msg.obj = device;
handler.sendMessage(msg);
}
}
@Override
public void onMtuChanged(BluetoothDevice device, int mtu) {
super.onMtuChanged(device, mtu);
}
};
#3
问题知道了,原因是app连接异常断开,但是发通知模块未做处理导致
#4
使用notifyCharacteristicChanged,未进入onNotificationSent的回调,楼主可否告知原因,万分感激。