转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持!


假设还有同学不知道蓝牙4.0能够做什么请查看Android+蓝牙 4.0 将带来什么?。如今能够穿戴设备也大多用的是蓝牙4.0,如 智能体质秤,智能手环,智能血压计等等。

原文地址:http://developer.android.com/guide/topics/connectivity/bluetooth-le.html

安卓4.3(API 18)为BLE的核心功能提供平台支持和API,App能够利用它来发现设备、查询服务和读写特性。相比传统的蓝牙,BLE更显著的特点是低功耗。

这一长处使android App能够与具有低功耗要求的BLE设备通信。如近距离传感器、心脏速率监视器、健身设备等。

关键术语和概念


  • Generic Attribute Profile(GATT)—GATT配置文件是一个通用规范。用于在BLE链路上发送和接收被称为“属性”的数据块。眼下全部的BLE应用都基于GATT。 蓝牙SIG规定了很多低功耗设备的配置文件。

    配置文件是设备怎样在特定的应用程序中工作的规格说明。注意一个设备能够实现多个配置文件。

    比如,一个设备可能包含心率监測仪和电量检測。

  • Attribute Protocol(ATT)—GATT在ATT协议基础上建立。也被称为GATT/ATT。

    ATT对在BLE设备上执行进行了优化。为此。它使用了尽可能少的字节。每一个属性通过一个唯一的的统一标识符(UUID)来标识。每一个String类型UUID使用128 bit标准格式。属性通过ATT被格式化为characteristics和services。

  • Characteristic 一个characteristic包含一个单一变量和0-n个用来描写叙述characteristic变量的descriptor,characteristic能够被觉得是一个类型。类似于类。
  • Descriptor Descriptor用来描写叙述characteristic变量的属性。比如。一个descriptor能够规定一个可读的描写叙述,或者一个characteristic变量可接受的范围。或者一个characteristic变量特定的測量单位。
  • Service service是characteristic的集合。比如。你可能有一个叫“Heart Rate Monitor(心率监測仪)”的service,它包含了非常多characteristics,如“heart rate measurement(心率測量)”等。你能够在bluetooth.org 找到一个眼下支持的基于GATT的配置文件和服务列表。

角色和责任

下面是Android设备与BLE设备交互时的角色和责任:

  • 中央 VS 外围设备。 适用于BLE连接本身。中央设备扫描,寻找广播;外围设备发出广播。
  • GATT 服务端 VS GATT client。

    决定了两个设备在建立连接后怎样互相交流。

为了方便理解,想象你有一个Android手机和一个用于活动跟踪BLE设备。手机支持中央角色,活动跟踪器支持外围(为了建立BLE连接你须要注意两件事,仅仅支持外围设备的双方或者仅仅支持中央设备的双方不能互相通信)。

当手机和运动追踪器建立连接后,他们開始向还有一方传输GATT数据。哪一方作为server取决于他们数据传输的种类。比如,假设运动追踪器想向手机报告传感器数据,运动追踪器是服务端。假设运动追踪器更新来自手机的数据。手机会作为服务端。

在这份文档的样例中。android app(执行在android设备上)作为GATTclient。app从gatt服务端获得数据,gatt服务端即支持Heart Rate Profile(心率配置)的BLE心率监測仪。可是你能够自己设计android app去扮演GATT服务端角色。很多其它信息见BluetoothGattServer。

BLE权限


为了在app中使用蓝牙功能,必须声明蓝牙权限BLUETOOTH。利用这个权限去运行蓝牙通信。比如请求连接、接受连接、和数据传输。

假设想让你的app启动设备发现或操纵蓝牙设置,必须声明BLUETOOTH_ADMIN权限。注意:假设你使用BLUETOOTH_ADMIN权限,你也必须声明BLUETOOTH权限。

在你的app manifest文件里声明蓝牙权限。

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

假设想声明你的app仅仅为具有BLE的设备提供,在manifest文件里包含:


<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

可是假设想让你的app提供给那些不支持BLE的设备,须要在manifest中包含上面代码并设置required="false",然后在执行时能够通过使用PackageManager.hasSystemFeature()确定BLE的可用性。

<span style="font-size:14px;font-weight: normal;">// 使用此检查确定BLE是否支持在设备上,然后你能够有选择性禁用BLE相关的功能
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();finish();
}</span>

设置BLE

你的app能与BLE通信之前,你须要确认设备是否支持BLE,假设支持,确认已经启用。

注意假设<uses-feature.../>设置为false,这个检查才是必需的。

假设不支持BLE,那么你应该适当地禁用部分BLE功能。假设支持BLE但被禁用,你能够无需离开应用程序而要求用户启动蓝牙。

使用BluetoothAdapter两步完毕该设置。

  1. 获取 BluetoothAdapter

    全部的蓝牙活动都须要蓝牙适配器。

    BluetoothAdapter代表设备本身的蓝牙适配器(蓝牙无线)。

    整个系统仅仅有一个蓝牙适配器,并且你的app使用它与系统交互。以下的代码片段显示了怎样得到适配器。

    注意该方法使用getSystemService()]返回BluetoothManager,然后将其用于获取适配器的一个实例。Android 4.3(API 18)引入BluetoothManager。

// 初始化蓝牙适配器
final BluetoothManager bluetoothManager =(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();

  1. 开启蓝牙

    接下来。你须要确认蓝牙是否开启。调用isEnabled())去检測蓝牙当前是否开启。假设该方法返回false,蓝牙被禁用。以下的代码检查蓝牙是否开启。假设没有开启,将显示错误提示用户去设置开启蓝牙。

// 确保蓝牙在设备上能够开启
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

发现BLE设备


为了发现BLE设备。使用startLeScan())方法。这种方法须要一个參数BluetoothAdapter.LeScanCallback。你必须实现它的回调函数,那就是返回的扫描结果。

由于扫描很消耗电量。你应当遵守下面准则:

  • 仅仅要找到所需的设备。停止扫描。
  • 不要在循环里扫描,而且对扫描设置时间限制。曾经可用的设备可能已经移出范围,继续扫描消耗电池电量。

以下代码显示了怎样開始和停止一个扫描:

/*** 扫描和显示能够提供的蓝牙设备.*/
public class DeviceScanActivity extends ListActivity {private BluetoothAdapter mBluetoothAdapter;private boolean mScanning;private Handler mHandler;// 10秒后停止寻找.private static final long SCAN_PERIOD = 10000;...private void scanLeDevice(final boolean enable) {if (enable) {// 经过预定扫描期后停止扫描mHandler.postDelayed(new Runnable() {@Overridepublic void run() {mScanning = false;mBluetoothAdapter.stopLeScan(mLeScanCallback);}}, SCAN_PERIOD);mScanning = true;mBluetoothAdapter.startLeScan(mLeScanCallback);} else {mScanning = false;mBluetoothAdapter.stopLeScan(mLeScanCallback);}...}
...
}

作为BLE扫描结果的接口,以下是BluetoothAdapter.LeScanCallback的实现。

假设你仅仅想扫描指定类型的外围设备,能够改为调用startLeScan(UUID[], BluetoothAdapter.LeScanCallback)),须要提供你的app支持的GATT services的UUID对象数组。

private LeDeviceListAdapter mLeDeviceListAdapter;
...
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =new BluetoothAdapter.LeScanCallback() {@Overridepublic void onLeScan(final BluetoothDevice device, int rssi,byte[] scanRecord) {runOnUiThread(new Runnable() {@Overridepublic void run() {mLeDeviceListAdapter.addDevice(device);mLeDeviceListAdapter.notifyDataSetChanged();}});}
};

连接到GATT服务端注意:仅仅能扫描BLE设备或者扫描传统蓝牙设备,不能同一时候扫描BLE和传统蓝牙设备。


与一个BLE设备交互的第一步就是连接它——更详细的。连接到BLE设备上的GATT服务端。为了连接到BLE设备上的GATT服务端,须要使用connectGatt( )方法。这种方法须要三个參数:一个Context对象。自己主动连接(boolean值,表示仅仅要BLE设备可用是否自己主动连接到它),和BluetoothGattCallback调用。

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);

在这个样例中,这个BLE APP提供了一个activity(DeviceControlActivity)来连接,显示数据。显示该设备支持的GATT services和characteristics。

依据用户的输入。这个activity与BluetoothLeService通信。通过Android BLE API实现与BLE设备交互。连接到GATT服务端时,由BLE设备做主机。并返回一个BluetoothGatt实例,然后你能够使用这个实例来进行GATTclient操作。请求方(Android app)是GATTclient。BluetoothGattCallback用于传递结果给用户。比如连接状态,以及不论什么进一步GATTclient操作。

//通过BLE API服务端与BLE设备交互
public class BluetoothLeService extends Service {private final static String TAG = BluetoothLeService.class.getSimpleName();private BluetoothManager mBluetoothManager; //蓝牙管理器private BluetoothAdapter mBluetoothAdapter; //蓝牙适配器private String mBluetoothDeviceAddress; //蓝牙设备地址private BluetoothGatt mBluetoothGatt; private int mConnectionState = STATE_DISCONNECTED;private static final int STATE_DISCONNECTED = 0; //设备无法连接private static final int STATE_CONNECTING = 1;  //设备正在连接状态private static final int STATE_CONNECTED = 2;   //设备连接完成public final static String ACTION_GATT_CONNECTED ="com.example.bluetooth.le.ACTION_GATT_CONNECTED";public final static String ACTION_GATT_DISCONNECTED ="com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";public final static String ACTION_GATT_SERVICES_DISCOVERED ="com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";public final static String ACTION_DATA_AVAILABLE ="com.example.bluetooth.le.ACTION_DATA_AVAILABLE";public final static String EXTRA_DATA ="com.example.bluetooth.le.EXTRA_DATA";public final static UUID UUID_HEART_RATE_MEASUREMENT =UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);//通过BLE API的不同类型的回调方法private final BluetoothGattCallback mGattCallback =new BluetoothGattCallback() {@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status,int newState) {//当连接状态发生改变String intentAction;if (newState == BluetoothProfile.STATE_CONNECTED) {//当蓝牙设备已经连接intentAction = ACTION_GATT_CONNECTED;mConnectionState = STATE_CONNECTED;broadcastUpdate(intentAction);Log.i(TAG, "Connected to GATT server.");Log.i(TAG, "Attempting to start service discovery:" +mBluetoothGatt.discoverServices());} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {//当设备无法连接intentAction = ACTION_GATT_DISCONNECTED;mConnectionState = STATE_DISCONNECTED;Log.i(TAG, "Disconnected from GATT server.");broadcastUpdate(intentAction);}}@Override// 发现新服务端public void onServicesDiscovered(BluetoothGatt gatt, int status) {if (status == BluetoothGatt.GATT_SUCCESS) {broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);} else {Log.w(TAG, "onServicesDiscovered received: " + status);}}@Override// 读写特性public void onCharacteristicRead(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic,int status) {if (status == BluetoothGatt.GATT_SUCCESS) {broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);}}...};
...
}

当一个特定的回调被触发的时候,它会调用对应的broadcastUpdate()辅助方法而且传递给它一个action。注意在该部分中的数据解析依照蓝牙心率測量配置文件规格进行。

private void broadcastUpdate(final String action) {final Intent intent = new Intent(action);sendBroadcast(intent);
}
private void broadcastUpdate(final String action,final BluetoothGattCharacteristic characteristic) {final Intent intent = new Intent(action);// 这是心率測量配置文件。if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {int flag = characteristic.getProperties();int format = -1;if ((flag & 0x01) != 0) {format = BluetoothGattCharacteristic.FORMAT_UINT16;Log.d(TAG, "Heart rate format UINT16.");} else {format = BluetoothGattCharacteristic.FORMAT_UINT8;Log.d(TAG, "Heart rate format UINT8.");}final int heartRate = characteristic.getIntValue(format, 1);Log.d(TAG, String.format("Received heart rate: %d", heartRate));intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));} else {// 对于全部其它的配置文件,用十六进制格式写数据final byte[] data = characteristic.getValue();if (data != null && data.length > 0) {final StringBuilder stringBuilder = new StringBuilder(data.length);for(byte byteChar : data)stringBuilder.append(String.format("%02X ", byteChar));intent.putExtra(EXTRA_DATA, new String(data) + "\n" +stringBuilder.toString());}}sendBroadcast(intent);
}

返回DeviceControlActivity, 这些事件由一个BroadcastReceiver来处理:

// 通过服务控制不同的事件
// ACTION_GATT_CONNECTED: 连接到GATT服务端
// ACTION_GATT_DISCONNECTED: 未连接GATT服务端.
// ACTION_GATT_SERVICES_DISCOVERED: 未发现GATT服务.
// ACTION_DATA_AVAILABLE: 接受来自设备的数据,能够通过读或通知操作获得。

private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) { mConnected = true; updateConnectionState(R.string.connected); invalidateOptionsMenu(); } 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)) { // 在用户接口上展示全部的services and characteristics displayGattServices(mBluetoothLeService.getSupportedGattServices()); } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) { displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)); } } };

读取BLE变量

你的android app完毕与GATT服务端连接和发现services后。就能够读写支持的属性。

比如。这段代码通过服务端的services和 characteristics迭代,而且将它们显示在UI上。

public class DeviceControlActivity extends Activity {...// 演示怎样遍历支持GATT Services/Characteristics// 这个样例中,我们填充绑定到UI的ExpandableListView上的数据结构private void displayGattServices(List<BluetoothGattService> gattServices) {if (gattServices == null) return;String uuid = null;String unknownServiceString = getResources().getString(R.string.unknown_service);String unknownCharaString = getResources().getString(R.string.unknown_characteristic);ArrayList<HashMap<String, String>> gattServiceData =new ArrayList<HashMap<String, String>>();ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData= new ArrayList<ArrayList<HashMap<String, String>>>();mGattCharacteristics =new ArrayList<ArrayList<BluetoothGattCharacteristic>>();// 循环可用的GATT Services.for (BluetoothGattService gattService : gattServices) {HashMap<String, String> currentServiceData =new HashMap<String, String>();uuid = gattService.getUuid().toString();currentServiceData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));currentServiceData.put(LIST_UUID, uuid);gattServiceData.add(currentServiceData);ArrayList<HashMap<String, String>> gattCharacteristicGroupData =new ArrayList<HashMap<String, String>>();List<BluetoothGattCharacteristic> gattCharacteristics =gattService.getCharacteristics();ArrayList<BluetoothGattCharacteristic> charas =new ArrayList<BluetoothGattCharacteristic>();// 循环可用的Characteristics.for (BluetoothGattCharacteristic gattCharacteristic :gattCharacteristics) {charas.add(gattCharacteristic);HashMap<String, String> currentCharaData =new HashMap<String, String>();uuid = gattCharacteristic.getUuid().toString();currentCharaData.put(LIST_NAME, SampleGattAttributes.lookup(uuid,unknownCharaString));currentCharaData.put(LIST_UUID, uuid);gattCharacteristicGroupData.add(currentCharaData);}mGattCharacteristics.add(charas);gattCharacteristicData.add(gattCharacteristicGroupData);}...}
...
}

接收GATT通知


当设备上的特性改变时会通知BLE应用程序。

这段代码显示了怎样使用setCharacteristicNotification( )给一个特性设置通知。

private BluetoothGatt mBluetoothGatt;
BluetoothGattCharacteristic characteristic;
boolean enabled;
...
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
...
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
mBluetoothGatt.writeDescriptor(descriptor);

假设对一个特性启用通知,当远程蓝牙设备特性发送变化,回调函数onCharacteristicChanged( ))被触发。

@Override
// 广播更新
public void onCharacteristicChanged(BluetoothGatt gatt,BluetoothGattCharacteristic characteristic) {broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}

关闭clientApp


当你的app完毕BLE设备的使用后,应该调用close( )),系统能够合理释放占用资源。

public void close() {if (mBluetoothGatt == null) {return;}mBluetoothGatt.close();mBluetoothGatt = null;
}

ym——物联网入口之中的一个Android蓝牙4.0相关推荐

  1. ym——物联网入口之一Android蓝牙4.0

    转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持! 如果还有同学不知道蓝牙4.0可以做什么请查看Android+蓝牙 4.0 将带来什么? ...

  2. android蓝牙4.0 BLE低功耗应用

    转自    http://www.cnblogs.com/zdz8207/archive/2012/10/17/bluetooth_ble_android.html 谈谈几个月以来开发android蓝 ...

  3. 谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受

    谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受 谈谈几个月以来开发android蓝牙4.0 BLE低功耗应用的感受,注明下时间:2012-10-17写的博客,后期更新的也注明了时间 ...

  4. 开发android蓝牙4.0 BLE低功耗应用的感受

    文章转自: http://www.cnblogs.com/zdz8207/archive/2012/10/17/bluetooth_ble_android.html 谈谈几个月以来开发android蓝 ...

  5. Android 蓝牙4.0(BLE)Demo

    给大家分享一下蓝牙4.0的Demo,本篇介绍基本使用 最终效果 如何获取UUID 使用 Android 蓝牙4.0(BLE) Demo下载 最终效果 如何获取UUID 去手机华为应用市场下载一个叫蓝牙 ...

  6. android 蓝牙4.0(BLE) 开发

    简介 蓝牙发展至今经历了9个版本的更新.1.1.1.2.2.0.2.1.3.0.4.0.4.1.4.2.5.0.那么在1.x~3.0之间的我们称之为传统蓝牙,4.x开始的蓝牙我们称之为低功耗蓝牙也就是 ...

  7. Android蓝牙4.0的数据通讯

    我在两家公司都用到了app与BLE设备通讯,当时也是什么都不懂,在网上各种搜索,各种查资料,总算弄出来了.在这里记录下来,希望对有需要的人有些帮助.   1.检测手机是否支持蓝牙4.0(一般手机4.3 ...

  8. Android蓝牙4.0 BLE开发坑总结

    onServicesDiscovered 回调里不能直接执行 write /readDataFromCharacteristic() 或者 enableNotificationOfCharacteri ...

  9. Android蓝牙4.0开发及发送指令到蓝牙硬件设备,简单好用,方法已写好直接可用

    近日,接到需要用到蓝牙解锁硬件设备的新需求,开发过程中呢也遇到许多硬件的坑,开发协议文档较简单,几句话就完了,第一次搞得我自己一脸懵逼,本来一两个小时就能写完并测试完成的过程用了两三天.哎!默默地回到 ...

最新文章

  1. 关于Windows 2003下开启防火墙后不能通过FTP问题解决
  2. 【牛客挑战赛】我是 A 题
  3. 最简单的基于librtmp的示例:接收(RTMP保存为FLV)
  4. leetcode 417. Pacific Atlantic Water Flow | 417. 太平洋大西洋水流问题(DFS,经典“感染”思路)
  5. php 判断当前栏目高亮,Phpcms V9采用if语句判断当前栏目高亮、判断分类信息是否过期...
  6. uni-app 组件传值
  7. 更快地重复访问Java的Java类名?
  8. GDB 调试程序 详解 使用实例
  9. c语言拔河分组回溯算法,【阅读下面的文字,完成10—12题。文明的共相回溯我们历史演-查字典问答网...
  10. 洛谷 P1031 均分纸牌【交叉模拟】
  11. 【报告分享】2020中国数字化后浪:中小企业转型与创新实录.pdf(附下载链接)...
  12. 美国人用什么android手机,美国过半消费者使用智能手机 Android占48.5%
  13. Xcode7.1模拟器卡顿问题以及解决方案
  14. Switch分支判断学习心得
  15. nvme-cli tool 刷FW(固件)
  16. 计算机方面发什么类型的论文,计算机类本科毕业论文
  17. 在ROS中创建工作区时出现错误
  18. Go语法·类型选择(type switch)
  19. Hexo+Github免费搭建个人博客+美化详细教程
  20. 怎么样才能在服务器显示皮肤,lol生涯怎么显示皮肤,手把手教你设置lol生涯皮肤显示...

热门文章

  1. SpringBoot使用H2内嵌数据库
  2. vue-cli+webpack打包配置
  3. windows 2003 迁移域控制器到 windows 2008
  4. 深入Java集合学习系列:Hashtable的实现原理
  5. fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64
  6. Android使用相机demo
  7. Trie树的C++实现
  8. Word无法读取此文档,文档可能已损坏
  9. 硬编码是什么意思_饰品上那些编码和数字你都知道是什么意思吗?
  10. 数据挖掘的步骤有哪些