Java 是否在OnServicesDiscovery()之后设置写入特征或在OnServicesDiscovery()之后设置广播方法?
我正在尝试创建BLE模块,如下所示:Java 是否在OnServicesDiscovery()之后设置写入特征或在OnServicesDiscovery()之后设置广播方法?,java,android,bluetooth-lowenergy,Java,Android,Bluetooth Lowenergy,我正在尝试创建BLE模块,如下所示: Connect -> Discover Service -> Auto Set characteristics -> Send checkSum Bytes 如果设备在10秒内无法接收字节,则蓝牙连接会自动断开 在实践中,即使我设置了后台线程发送校验和字节,蓝牙连接也会自动断开。我发现创建处理程序消息太难了,无法通过广播将消息从BLuetoothLeService返回到主活动。即使我已经声明立即查找服务和特征,在发送字节之前也没有得到响应
Connect -> Discover Service -> Auto Set characteristics -> Send checkSum Bytes
如果设备在10秒内无法接收字节,则蓝牙连接会自动断开
在实践中,即使我设置了后台线程
发送校验和字节,蓝牙连接也会自动断开。我发现创建处理程序消息太难了,无法通过广播将消息从BLuetoothLeService返回到主活动。即使我已经声明立即查找服务和特征,在发送字节之前也没有得到响应。您能告诉我应该找到和设置哪种回调方法吗
以下是我的工作经历:
DeviceControlActivity.java
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG , "Unable to initialize Bluetooth");
finish();
}
mBluetoothLeService.connect(mDeviceAddress);
mBluetoothLeService.setBLEServiceCb(mDCServiceCb);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
int status = intent.getIntExtra(BluetoothLeService.EXTRA_STATUS, BluetoothGatt.GATT_SUCCESS);
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
if(BluetoothLeService.getBtGatt() != null)
{
BluetoothLeService.getBtGatt().discoverServices();
}
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
displayGattServices(mBluetoothLeService.getSupportedGattServices());
}
else if (BluetoothLeService.ACTION_DATA_NOTIFY.equals(action)) {
// Notification
byte [] value = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
String uuidStr = intent.getStringExtra(BluetoothLeService.EXTRA_UUID);
boolean isFloat = intent.getBooleanExtra(BluetoothLeService.EXTRA_FLOAT, false);
packetLength = intent.getIntExtra(BluetoothLeService.EXTRA_LENGTH, 20);
System.out.println("status B : " + isFloat);
if(isFloat){
onCharacteristicChangedWithParam(uuidStr, value);
}else{
onCharacteristicChanged(uuidStr, value);
}
} else if (BluetoothLeService.ACTION_DATA_WRITE.equals(action)) {
// Data written
String uuidStr = intent.getStringExtra(BluetoothLeService.EXTRA_UUID);
onCharacteristicWrite(uuidStr,status);
} else if (BluetoothLeService.ACTION_DATA_READ.equals(action)) {
// Data read
String uuidStr = intent.getStringExtra(BluetoothLeService.EXTRA_UUID);
byte [] value = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
onCharacteristicsRead(uuidStr,value,status);
}
}
};
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device. */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BluetoothLeService extends Service {
public static BluetoothGatt getBtGatt() {
return mBluetoothGatt;
}
public static BluetoothManager getBtManager() {
return mThis.mBluetoothManager;
}
public static BluetoothLeService getInstance() {
return mThis;
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (mBluetoothGatt == null) {
Log.e(TAG , "mBluetoothGatt not created!");
// return;
}
BluetoothDevice device = gatt.getDevice();
String address = device.getAddress();
// Log.d("onConnectionStateChange status = " + status + ", newState = " + newState);
try {
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
broadcastUpdate(ACTION_GATT_CONNECTED, address, status);
startReadRssi();
break;
case BluetoothProfile.STATE_DISCONNECTED:
broadcastUpdate(ACTION_GATT_DISCONNECTED, address, status);
stopReadRssi();
break;
default:
Log.e(TAG , "New state not processed: " + newState);
break;
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
BluetoothDevice device = gatt.getDevice();
BluetoothGattService rblService = mBluetoothGatt.getService(U_ABC_SERVICE);
if (rblService == null) {
Log.e(TAG, "RBL service not found!");
return;
}
List<BluetoothGattCharacteristic> Characteristic = rblService
.getCharacteristics();
for (BluetoothGattCharacteristic a : Characteristic) {
Log.e(TAG, " a = uuid : " + a.getUuid() + "");
}
setReadChar();
mWriteCharacteristic = rblService.getCharacteristic(U_ABC_W_CHARACTERISTIC);
if (mWriteCharacteristic == null) {
Log.e(TAG, "RBL TX Characteristic not found!");
return;
}
mCmdCharacteristic = rblService.getCharacteristic(U_ABC_C_CHARACTERISTIC);
if (mCmdCharacteristic == null) {
Log.e(TAG, "RBL CMD Characteristic not found!");
return;
}
// List<BluetoothGattService> gattServices = gatt.getServices();
/*
mWriteService = gatt.getService(U_ABC_SERVICE);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCmdCharacteristic = mWriteService.getCharacteristic(U_ABC_C_CHARACTERISTIC);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setReadChar();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mWriteCharacteristic = mWriteService.getCharacteristic(U_ABC_W_CHARACTERISTIC);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED, device.getAddress(), status);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
//readCharacteristicQueue.remove();
broadcastUpdate(ACTION_DATA_NOTIFY, characteristic , BluetoothGatt.GATT_SUCCESS);
}
BluetoothLeService.java
private final ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG , "Unable to initialize Bluetooth");
finish();
}
mBluetoothLeService.connect(mDeviceAddress);
mBluetoothLeService.setBLEServiceCb(mDCServiceCb);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
int status = intent.getIntExtra(BluetoothLeService.EXTRA_STATUS, BluetoothGatt.GATT_SUCCESS);
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
if(BluetoothLeService.getBtGatt() != null)
{
BluetoothLeService.getBtGatt().discoverServices();
}
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
clearUI();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
// Show all the supported services and characteristics on the user interface.
displayGattServices(mBluetoothLeService.getSupportedGattServices());
}
else if (BluetoothLeService.ACTION_DATA_NOTIFY.equals(action)) {
// Notification
byte [] value = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
String uuidStr = intent.getStringExtra(BluetoothLeService.EXTRA_UUID);
boolean isFloat = intent.getBooleanExtra(BluetoothLeService.EXTRA_FLOAT, false);
packetLength = intent.getIntExtra(BluetoothLeService.EXTRA_LENGTH, 20);
System.out.println("status B : " + isFloat);
if(isFloat){
onCharacteristicChangedWithParam(uuidStr, value);
}else{
onCharacteristicChanged(uuidStr, value);
}
} else if (BluetoothLeService.ACTION_DATA_WRITE.equals(action)) {
// Data written
String uuidStr = intent.getStringExtra(BluetoothLeService.EXTRA_UUID);
onCharacteristicWrite(uuidStr,status);
} else if (BluetoothLeService.ACTION_DATA_READ.equals(action)) {
// Data read
String uuidStr = intent.getStringExtra(BluetoothLeService.EXTRA_UUID);
byte [] value = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
onCharacteristicsRead(uuidStr,value,status);
}
}
};
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device. */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class BluetoothLeService extends Service {
public static BluetoothGatt getBtGatt() {
return mBluetoothGatt;
}
public static BluetoothManager getBtManager() {
return mThis.mBluetoothManager;
}
public static BluetoothLeService getInstance() {
return mThis;
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (mBluetoothGatt == null) {
Log.e(TAG , "mBluetoothGatt not created!");
// return;
}
BluetoothDevice device = gatt.getDevice();
String address = device.getAddress();
// Log.d("onConnectionStateChange status = " + status + ", newState = " + newState);
try {
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
broadcastUpdate(ACTION_GATT_CONNECTED, address, status);
startReadRssi();
break;
case BluetoothProfile.STATE_DISCONNECTED:
broadcastUpdate(ACTION_GATT_DISCONNECTED, address, status);
stopReadRssi();
break;
default:
Log.e(TAG , "New state not processed: " + newState);
break;
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
BluetoothDevice device = gatt.getDevice();
BluetoothGattService rblService = mBluetoothGatt.getService(U_ABC_SERVICE);
if (rblService == null) {
Log.e(TAG, "RBL service not found!");
return;
}
List<BluetoothGattCharacteristic> Characteristic = rblService
.getCharacteristics();
for (BluetoothGattCharacteristic a : Characteristic) {
Log.e(TAG, " a = uuid : " + a.getUuid() + "");
}
setReadChar();
mWriteCharacteristic = rblService.getCharacteristic(U_ABC_W_CHARACTERISTIC);
if (mWriteCharacteristic == null) {
Log.e(TAG, "RBL TX Characteristic not found!");
return;
}
mCmdCharacteristic = rblService.getCharacteristic(U_ABC_C_CHARACTERISTIC);
if (mCmdCharacteristic == null) {
Log.e(TAG, "RBL CMD Characteristic not found!");
return;
}
// List<BluetoothGattService> gattServices = gatt.getServices();
/*
mWriteService = gatt.getService(U_ABC_SERVICE);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mCmdCharacteristic = mWriteService.getCharacteristic(U_ABC_C_CHARACTERISTIC);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setReadChar();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mWriteCharacteristic = mWriteService.getCharacteristic(U_ABC_W_CHARACTERISTIC);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED, device.getAddress(), status);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
//readCharacteristicQueue.remove();
broadcastUpdate(ACTION_DATA_NOTIFY, characteristic , BluetoothGatt.GATT_SUCCESS);
}
/**
*用于管理与托管在服务器上的GATT服务器的连接和数据通信的服务
*给定蓝牙设备*/
@TargetApi(Build.VERSION\u code.JELLY\u BEAN\u MR2)
公共类BluetoothLeService扩展服务{
公共静态蓝牙gatt getBtGatt(){
返回关贸总协定;
}
公共静态BluetoothManager getBtManager(){
返回mThis.mBluetoothManager;
}
公共静态BluetoothLeService getInstance(){
返回mThis;
}
私有最终BluetoothGattCallback mGattCallback=新BluetoothGattCallback(){
@凌驾
连接状态更改的公共无效(蓝牙gatt gatt、int状态、int新闻状态){
if(mBluetoothGatt==null){
Log.e(标记“MBlueTothGatt未创建!”);
//返回;
}
BluetoothDevice=gatt.getDevice();
字符串地址=device.getAddress();
//Log.d(“onConnectionStateChange status=“+status+”,newState=“+newState”);
试一试{
交换机(新闻状态){
案例BluetoothProfile.STATE\u已连接:
广播更新(已连接行动、地址、状态);
startrederssi();
打破
案例BluetoothProfile.STATE\u已断开连接:
广播更新(动作、地址、状态);
stopReadRssi();
打破
违约:
Log.e(标签,“未处理的新状态:“+newState”);
打破
}
}捕获(NullPointerException e){
e、 printStackTrace();
}
}
@凌驾
发现服务上的公共无效(Bluetooth gatt,int状态){
BluetoothDevice=gatt.getDevice();
BluetoothGattService rblService=mbluetothGatt.getService(U_ABC_服务);
if(rblService==null){
Log.e(标记“未找到RBL服务!”);
返回;
}
列表特征=rblService
.getCharacteristics();
for(蓝牙特征a:特征){
Log.e(标记“a=uuid:+a.getUuid()+”);
}
setReadChar();
mWriteCharacteristic=rblService.getCharacteristic(U_ABC_W_CHARACTERISTIC);
if(mWriteCharacteristic==null){
Log.e(标签“未找到RBL发送特征!”);
返回;
}
mCmdCharacteristic=rblService.getCharacteristic(U_ABC_C_CHARACTERISTIC);
if(mCmdCharacteristic==null){
Log.e(标记“未找到RBL CMD特征!”);
返回;
}
//List gattServices=gatt.getServices();
/*
mWriteService=gatt.getService(U_ABC_SERVICE);
试一试{
睡眠(200);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
mCmdCharacteristic=mWriteService.getCharacteristic(U_ABC_C_CHARACTERISTIC);
试一试{
睡眠(200);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
setReadChar();
试一试{
睡眠(200);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
mWriteCharacteristic=mWriteService.getCharacteristic(U_ABC_W_CHARACTERISTIC);
试一试{
睡眠(200);
}捕捉(中断异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}*/
如果(状态==蓝牙GATT.GATT\U成功){
广播更新(操作\u GATT\u服务\u发现,设备.getAddress(),状态);
}
}
@凌驾
特征变更后的公共无效(蓝牙gatt,
蓝牙(特征){
//readCharacteristicQueue.remove();
广播更新(行动、数据、通知、特征、蓝牙GATT.GATT成功);
}