- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试编写一个 Android 应用程序来模仿我编写的 iOS 应用程序中已经存在的功能。我正在连接 2 个不同的 BLE 设备:
在 iOS 上,我的两台设备都运行良好并报告数据。在 Android 上,我无法让它工作。经过数小时的研究和测试,我认为我要解决的基本问题是:
在 iOS 上,我调用以下代码使 BLE 设备在有数据要报告时通知我的 iOS 设备:
#pragma mark - CBPeripheralDelegate Protocol methods
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
for (CBCharacteristic *characteristic in [service characteristics]) {
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
就是这样。 iOS 中此方法的说明如下:
If the specified characteristic is configured to allow both notifications and indications, calling this method enables notifications only.
基于此(以及 它在 iOS 中工作 的事实),我认为我想要通知的特性的配置描述符应该像这样配置:
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
gatt.writeDescriptor(descriptor);
考虑到这一点,我的 BLEDevice
类如下所示:
public abstract class BLEDevice {
protected BluetoothAdapter.LeScanCallback mLeScanCallback;
protected BluetoothGattCallback mBluetoothGattCallback;
protected byte[] mBytes;
protected Context mContext;
protected GotReadingCallback mGotReadingCallback;
protected String mDeviceName;
public final static UUID UUID_WEIGHT_SCALE_SERVICE
= UUID.fromString(GattAttributes.WEIGHT_SCALE_SERVICE);
public final static UUID UUID_WEIGHT_SCALE_READING_CHARACTERISTIC
= UUID.fromString(GattAttributes.WEIGHT_SCALE_READING_CHARACTERISTIC);
public final static UUID UUID_WEIGHT_SCALE_CONFIGURATION_CHARACTERISTIC
= UUID.fromString(GattAttributes.WEIGHT_SCALE_CONFIGURATION_CHARACTERISTIC);
public final static UUID UUID_WEIGHT_SCALE_CONFIGURATION_DESCRIPTOR
= UUID.fromString(GattAttributes.WEIGHT_SCALE_CONFIGURATION_DESCRIPTOR);
abstract void processReading();
interface GotReadingCallback {
void gotReading(Object reading);
}
public BLEDevice(Context context, String deviceName, GotReadingCallback gotReadingCallback) {
mContext = context;
BluetoothManager btManager = (BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE);
final BluetoothAdapter btAdapter = btManager.getAdapter();
if (btAdapter != null && !btAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
mContext.startActivity(enableIntent);
}
mDeviceName = deviceName;
mBluetoothGattCallback = new BluetoothGattCallback() {
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
byte[] data = characteristic.getValue();
mBytes = data;
Log.d("BluetoothGattCallback.onCharacteristicChanged", "data: " + data.toString());
}
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
// this will get called when a device connects or disconnects
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
if (mBytes != null) {
processReading();
}
}
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
Log.d("onDescriptorWrite", "descriptor: " + descriptor.getUuid() + ". characteristic: " + descriptor.getCharacteristic().getUuid() + ". status: " + status);
}
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
// this will get called after the client initiates a BluetoothGatt.discoverServices() call
BluetoothGattService service = gatt.getService(UUID_WEIGHT_SCALE_SERVICE);
if (service != null) {
BluetoothGattCharacteristic characteristic;
characteristic = service.getCharacteristic(UUID_WEIGHT_SCALE_READING_CHARACTERISTIC);
if (characteristic != null) {
gatt.setCharacteristicNotification(characteristic, true);
}
characteristic = service.getCharacteristic(UUID_WEIGHT_SCALE_CONFIGURATION_CHARACTERISTIC);
if (characteristic != null) {
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID_WEIGHT_SCALE_CONFIGURATION_DESCRIPTOR);
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
}
}
}
};
mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
Log.d("LeScanCallback", device.toString());
if (device.getName().contains("{Device Name}")) {
BluetoothGatt bluetoothGatt = device.connectGatt(mContext, false, mBluetoothGattCallback);
btAdapter.stopLeScan(mLeScanCallback);
}
}
};
btAdapter.startLeScan(mLeScanCallback);
}
}
NOTE: It might be important to know that these 2 devices function in the following way:
- The BLE device is turned on an a measurement is initiated on the device.
- Once the measurement has been taken, the BLE device attempts to initiate a BLE connection.
- Once the BLE connection is made, the device pretty much immediately sends the data, sometimes sending a couple of data packets. (If previous data measurements haven't been successfully sent over BLE, it keeps them in memory and sends all of them, so I only really care about the final data packet.)
- Once the final data packet is sent, the BLE device disconnects rapidly.
- If the BLE device fails to send data (as is currently happening on the Android app), the BLE device disconnects pretty rapidly.
在我的 LogCat 中,我看到很多输出完全符合我的预期。
我最近遇到的失败是在 onCharacteristicWrite
中报告状态“128”。对问题 #3(下方)的评论似乎表明这是一个资源问题。
我看过以下问题:
这就是为什么他们不给我我需要的东西:
我尝试了很多示例和教程,包括 Google 的 Android 示例代码。他们似乎都没有启用 BLE 设备来通知我的 Android 设备数据更新。它显然不是设备,因为 iOS 版本有效。那么,iOS 代码在后台做了什么来使通知正常工作,Android 端的哪些代码会模仿该功能?
根据@yonran 的评论,我更新了我的代码,将 onServicesDiscovered
实现更改为:
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
// this will get called after the client initiates a BluetoothGatt.discoverServices() call
BluetoothGattService service = gatt.getService(UUID_WEIGHT_SCALE_SERVICE);
if (service != null) {
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID_WEIGHT_SCALE_READING_CHARACTERISTIC);
if (characteristic != null) {
if (gatt.setCharacteristicNotification(characteristic, true) == true) {
Log.d("gatt.setCharacteristicNotification", "SUCCESS!");
} else {
Log.d("gatt.setCharacteristicNotification", "FAILURE!");
}
BluetoothGattDescriptor descriptor = characteristic.getDescriptors().get(0);
if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE)) {
// It's an indicate characteristic
Log.d("onServicesDiscovered", "Characteristic (" + characteristic.getUuid() + ") is INDICATE");
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
} else {
// It's a notify characteristic
Log.d("onServicesDiscovered", "Characteristic (" + characteristic.getUuid() + ") is NOTIFY");
if (descriptor != null) {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
}
}
}
}
}
那确实似乎改变了一些事情。这是当前的 Logcat,代码更改后:
D/BluetoothGatt﹕ setCharacteristicNotification() - uuid: <UUID> enable: true
D/gatt.setCharacteristicNotification﹕ SUCCESS!
D/onServicesDiscovered﹕ Characteristic (<UUID>) is INDICATE
D/BluetoothGatt﹕ writeDescriptor() - uuid: 00002902-0000-1000-8000-00805f9b34fb
D/BluetoothGatt﹕ onDescriptorWrite() - Device=D0:5F:B8:01:6C:9E UUID=<UUID>
D/onDescriptorWrite﹕ descriptor: 00002902-0000-1000-8000-00805f9b34fb. characteristic: <UUID>. status: 0
D/BluetoothGatt﹕ onClientConnectionState() - status=0 clientIf=6 device=D0:5F:B8:01:6C:9E
所以,看来我现在正在正确设置所有内容(因为 setCharacteristicNotification
返回 true
并且 onDescriptorWrite
状态为 0
)。但是,onCharacteristicChanged
仍然不会触发。
最佳答案
我已经能够通过以下方式成功捕获具有多个服务和特征的 onCharacteristicChanged():
服务发现完成后,在主循环中的 broadcastReceiver() 中写入描述符值。
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
//more code...
if (action.equals(uartservice.ACTION_GATT_SERVICES_DISCOVERED)) {
mService.enableTXNotification();
}
和
通过在描述符值设置之间添加延迟
public void enableTXNotification(){
/*
if (mBluetoothGatt == null) {
showMessage("mBluetoothGatt null" + mBluetoothGatt);
broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
return;
}
*/
/**
* Enable Notifications for the IO service and characteristic
*
*/
BluetoothGattService IOService = mBluetoothGatt.getService(IO_SERVICE_UUID);
if (IOService == null) {
showMessage("IO service not found!");
broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_IO);
return;
}
BluetoothGattCharacteristic IOChar = IOService.getCharacteristic(IO_CHAR_UUID);
if (IOChar == null) {
showMessage("IO charateristic not found!");
broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_IO);
return;
}
mBluetoothGatt.setCharacteristicNotification(IOChar,true);
BluetoothGattDescriptor descriptorIO = IOChar.getDescriptor(CCCD);
descriptorIO.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptorIO);
/**
* For some reason android (or the device) can't handle
* writing one descriptor after another properly. Without
* the delay only the first characteristic can be caught in
* onCharacteristicChanged() method.
*/
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* Enable Indications for the RXTX service and characteristic
*/
BluetoothGattService RxService = mBluetoothGatt.getService(RXTX_SERVICE_UUID);
if (RxService == null) {
showMessage("Rx service not found!");
broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
return;
}
BluetoothGattCharacteristic RxChar = RxService.getCharacteristic(RXTX_CHAR_UUID);
if (RxChar == null) {
showMessage("Tx charateristic not found!");
broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_UART);
return;
}
mBluetoothGatt.setCharacteristicNotification(RxChar,true);
BluetoothGattDescriptor descriptor = RxChar.getDescriptor(CCCD);
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE );
mBluetoothGatt.writeDescriptor(descriptor);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* Enable Notifications for the Battery service and Characteristic?
*/
BluetoothGattService batteryService = mBluetoothGatt.getService(BATTERY_SERVICE_UUID);
if (batteryService == null) {
showMessage("Battery service not found!");
broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_BATTERY);
return;
}
BluetoothGattCharacteristic batteryChar = batteryService.getCharacteristic(BATTERY_CHAR_UUID);
if (batteryChar == null) {
showMessage("Battery charateristic not found!");
broadcastUpdate(DEVICE_DOES_NOT_SUPPORT_BATTERY);
return;
}
}
关于安卓蓝牙 : onCharacteristicChanged never fires,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28586111/
我试图创建 Kindle Fire 模拟器来测试 Kindle Fire 平板电脑、Fire 手机和亚马逊电视的应用程序。我已经按照文档进行操作,但无法为这些创建模拟器。谁能告诉我亚马逊是否支持模拟器
以下代码运行大约需要 20 秒。然而,取消注释 do! 后只用了不到一秒的时间。为什么会有这么大的差异? 更新:使用ag.Add时需要9秒。我已经更新了代码。 open FSharpx.Control
我曾经将图像保存到 fire base storage 它在所有 android 设备上工作但在 amazon fire 上,它抛出错误。 这是日志 W/GooglePlayServicesUtil:
我想为 Fire TV 应用程序进行 Google 登录。不幸的是,我不能为此使用 Google Play 服务,所以我需要解决这个问题。我唯一能想到的就是让登录屏幕成为 uiwebview Goog
我们有 Gem Fire 6 数据,想将其迁移到 Gem Fire 8 数据。为此有哪些可能的选择?我们需要这个,因为我们的客户可能不乐意丢失 Gem Fire 6 服务器中的数据。请指教。 最佳答案
我是 Quartz 的新手,一直在重复作业运行。它们是由两个触发时间重叠的触发器引起的。 是否有任何 Quartz 的“开箱即用”功能可以防止重复触发具有多个附加触发器的同一作业? 或者也许有一些第三
我一直在尝试测试事件,昨天我让它工作了。那是在我开始重构测试代码以防止它过于重复之前。我添加了 setUp 方法调用以使用 ModelFactories 生成假数据。这是昨天在每个测试用例中完成的,并
我想在我关注文本区域之前触发一个事件(即在键盘出现在 iOS 上之前)。 这可能吗? 我处理焦点的代码在这里: $(document).on('focus', 'textarea', function
我使用 HTML5 和 JavaScript 开发了 Fire TV 应用程序。这里我需要识别当前访问的设备是什么。 Amazon Fire TV 或 Amazon Fire Stick。 如何使用
Angular 版本: @angular-devkit/architect 0.803.22 @angular-devkit/build-angular 0.803.22 @a
python包Fire对于从命令行启动 python 脚本非常有用。一件常见的事情是有由多个单词组成的参数,例如可以用 3 种通用方式编写的 cat 的名称: nameofcat name_of_ca
我正在尝试使用 javascript 检测我的网站是否在 kindle fire 移动设备上运行。我试过使用 navigator.userAgent 和 navigator.appVersion 但我
hi This : var fees=document.getElementById("conn"); var btn=document.getE
我在网上查过,但找不到任何东西: 如何摆脱在我正在观看的电影上显示的这个通知圈? 最佳答案 这个东西来自 ES 文件浏览器 只需进入此应用程序 > 设置 然后有一个选项说记录 float 窗口,你只需
我需要知道当用户通过新的 Fullscreen API 进入全屏模式时会触发哪些(DOM)事件。我尝试了这个片段,但它没有触发: jQuery('body').on('fullScreenChange
我试图通过在加载页面时隐藏 webView 来在不同网页的加载之间进行转换。但是,我发现一些图像密集型网站导致 webViewDidFinishLoading 过早触发,当我在此时显示 webView
我的应用程序使用 MVVM 模式。我的 TextBox绑定(bind)到我的 ViewModel 的属性(类型字符串)。 何时 TextBox 的内容通过用户输入更改,我想执行一些验证。 所以,目前,
有谁知道如何检测该应用程序是否在Kindle Fire上运行? 如果在Kindle Fire上运行,我的应用程序需要关闭一些功能,并且我想使用与Google Marketplace相同的版本。 最佳答
如何告诉 jQuery 仅触发一次回调函数? $(document).on('ready turbolinks:load', function callback_function() { co
使用新的HTML音频标签: Your browser does not support the audio element. 在我尝试过的所有浏览器(IE v10,Chrome v23,O
我是一名优秀的程序员,十分优秀!