低功耗蓝牙BLE外围模式(peripheral)-使用BLE作为服务端
Android对外模模式(peripheral)的支持
从Android5.0开始才支持
关键术语和概念
以下是关键BLE术语和概念的摘要:
通用属性简档(GATT) - GATT简档是用于通过BLE链路发送和接收称为“属性”的短数据块的一般规范。 所有当前的低能量应用配置文件都基于GATT。
蓝牙SIG为低能量设备定义了许多配置文件 。 配置文件是设备在特定应用程序中的工作方式的规范。 请注意,设备可以实现多个配置文件。 例如,设备可以包含心率监视器和电池水平检测器。
属性协议(ATT) -GATT建立在属性协议(ATT)之上。 这也称为GATT / ATT。 ATT经过优化,可在BLE设备上运行。 为此,它使用尽可能少的字节。 每个属性由通用唯一标识符(UUID)唯一标识,UUID是用于唯一标识信息的字符串ID的标准化128位格式。 由ATT传送的属性被格式化为特征和服务 。
特性 -A特性包含描述特性值的单个值和0-n个描述符。 一个特性可以被认为是一个类型,类似于类。
描述符 - 描述符是描述特征值的定义属性。 例如,描述符可以指定人类可读的描述,特征值的可接受范围或特征值的特定的测量单位。
服务 - 服务是一个集合的特点。 例如,您可以有一个名为“心率监视器”的服务,其中包括诸如“心率测量”的特征。 您可以在bluetooth.org上找到现有基于GATT的个人资料和服务的列表 。
角色和职责
以下是Android设备与BLE设备互动时适用的角色和职责:
中央与外围。 这适用于BLE连接本身。 处于中心角色的设备扫描,寻找广告,并且外围角色中的设备进行广告。
GATT服务器与GATT客户端。 这决定了两个设备在建立连接后如何相互通信。
BLE权限
首先,需要在manifest中声明使用蓝牙和操作蓝牙的权限
在应用程序清单文件中声明蓝牙权限。 例如:
如果您要声明自己的应用只适用于支持BLE的设备,请在应用清单中包含以下内容:
不过,如果您想让应用程式适用于不支援BLE的装置,您仍应在应用的清单中加入这个元素,但required="false"设为required="false" 。
然后在运行时,您可以通过使用PackageManager.hasSystemFeature()确定BLE可用性:
// Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
在android 6.0 以后,要想获得蓝牙扫描结果,还需要下面的权限
...
...
设置蓝牙
1.Get the BluetoothAdapter
获得蓝牙适配器
private BluetoothAdapter mBluetoothAdapter;
...
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
2.Enable Bluetooth
打开蓝牙
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
3.初始化BLE蓝牙广播(广告)
(1)广播的设置
(2)设置广播的数据
(3)设置响应的数据
(4)设置连接回调
private void initGATTServer() {
AdvertiseSettings settings = new AdvertiseSettings.Builder()
.setConnectable(true)
.build();
AdvertiseData advertiseData = new AdvertiseData.Builder()
.se