翻译的官方文档,原文在这里:点击打开链接 ,本人对部分内容进行了微调,大意和原文一致。
蓝牙低功耗
Android 4.3(API级别18)为处于中心角色的低能耗蓝牙(BLE)引入了内置的平台支持,并为应用程序提供了可用于发现设备,查询服务和传输信息的API。
- 在附近设备之间传输少量数据。
- 与Google Beacons等距离传感器进行交互,可以根据用户的当前位置为用户提供个性化的体验。
- 通用属性配置文件(GATT) - GATT配置文件是通过BLE链接发送和接收称为“属性”的短数据的通用规范。 所有当前的低能耗应用配置文件均基于GATT。
- Bluetooth SIG定义了低能耗设备的许多配置文件。 配置文件是设备在特定应用程序中如何工作的规范。 请注意,设备可以实现多个配置文件。 例如,设备可以包含心率监测器和电池电平检测器。
-
属性协议(ATT)-GATT建立在属性协议(ATT)之上。 这也被称为GATT / ATT。 ATT经过优化,可在BLE设备上运行。 为此,它使用尽可能少的字节。 每个属性由通用唯一标识符(UUID)唯一标识,该标识符是用于唯一标识信息的字符串ID的标准化128位格式。 由ATT传输的属性被格式化为特征和服务。
-
特征 - 特征包含描述特征值的单个值和0-n描述符。 一个特征可以被认为是一个类型,类似于一个类。
-
描述符 - 描述符是描述特征值的定义属性。 例如,描述符可以指定人类可读描述,特征值的可接受范围,或特定于特征值的特定度量单位。
-
服务 - 服务是特征的集合。 例如,您可以使用一个名为“心率监测器”的服务,其中包含“心率测量”等特征。 您可以在bluetooth.org上找到现有的基于GATT的配置文件和服务列表。
- 中央与外围。 这适用于BLE连接本身。处于中央角色的设备扫描,寻找蓝牙设备,处于外围角色中的设备则成为可连接的设备。
- GATT服务器与GATT客户端。 这确定了两个设备在建立连接之后如何对话。
BLE权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
如果您要声明您的应用仅适用于支持BLE的设备,请在应用的清单中包含以下内容:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
但是,如果您希望将应用程序提供给不支持BLE的设备,则应将此元素包含在应用程序的清单中,但setrequired =“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();
}
请求用户权限
为了从NETWORK_PROVIDER或GPS_PROVIDER接收位置更新,您必须在Android清单文件中声明{@code ACCESS_COARSE_LOCATION}或{@code ACCESS_FINE_LOCATION}权限来请求用户权限。 没有这些权限,您的应用程序对位置更新的请求将失败,并将显示权限错误。
<manifest >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />
</manifest>
设置BLE
-
获取BluetoothAdapterBluetoothAdapter是所有蓝牙活动所必需的。 BluetoothAdapter表示设备自己的蓝牙适配器(蓝牙无线电)。 整个系统有一个蓝牙适配器,您的应用程序可以使用此对象进行交互。 下面的代码片段显示了如何获取适配器。 请注意,此方法使用getSystemService()返回一个BluetoothManager实例,然后用于获取适配器。 Android 4.3(API Level 18)介绍了BluetoothManager:1
private BluetoothAdapter mBluetoothAdapter;
23// Initializes Bluetooth adapter.
4final BluetoothManager bluetoothManager =
5(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
6mBluetoothAdapter = bluetoothManager.getAdapter();
- 启用蓝牙
接下来,您需要确保启用蓝牙。 调用isEnabled()来检查蓝牙是否被启用。 如果此方法返回false,则蓝牙被禁用。 以下片段检查是否启用蓝牙。 如果不是,该片段会显示错误并提示用户进入设置以启用蓝牙:1// Ensures Bluetooth is available on the device and it is enabled. If not,
2// displays a dialog requesting user permission to enable Bluetooth.
3if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled())
4{
5Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
6startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
7}
注意:传递给startActivityForResult(android.content.Intent,int)的REQUEST_ENABLE_BT常量,是系统作为requestCode参数在您的onActivityResult(int,int,android.content.Intent) 实现 中,传回给您的本地定义的整数(必须大于0)。
查找BLE设备
To find BLE devices, you use the startLeScan() method. This method takes a BluetoothAdapter.LeScanCallback as a parameter. You must implement this callback, because that is how scan results are returned. Because scanning is battery-intensive, you should observe the following guidelines:
- 一旦找到所需的设备,请停止扫描。
- 切勿循环扫描,并应该设置扫描时间限制。 以前可用的设备可能已经超出扫描范围,持续的扫描会耗光电池电量。
/**
* Activity for scanning and displaying available BLE devices.
*/
public class DeviceScanActivity extends ListActivity
{
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
private void scanLeDevice(final boolean enable)
{
if (enable)
{
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable()
{
@Override
public void run()
{
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
else
{
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
}
private LeDeviceListAdapter mLeDeviceListAdapter;
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback()
{
@Override
public void onLeScan(final BluetoothDevice device, int rssi,
byte[] scanRecord)
{
runOnUiThread(new Runnable()
{
@Override
public void run()
{
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
连接到GATT服务器
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
// A service that interacts with the BLE device via the Android BLE API.
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);
// Various callback methods defined by the BLE API.
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback()
{
@Override
public 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
// New services discovered
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
// Result of a characteristic read operation
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status)
{
if (status == BluetoothGatt.GATT_SUCCESS)
{
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
};
}
当一个特定的回调被触发时,它调用相应的broadcastUpdate()辅助方法并传递一个动作。 请注意,本节中的数据解析是根据蓝牙心率测量配置文件规范执行的:
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);
}
回到设备控制活动,这些事件由BroadcastReceiver处理:
// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device. This can be a
// result of read or notification operations.
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))
{
// Show all the supported services and characteristics on the
// user interface.
displayGattServices(mBluetoothLeService.getSupportedGattServices());
}
else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action))
{
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
阅读BLE属性
public class DeviceControlActivity extends Activity
{
//演示如何迭代支持的GATT服务/特性。
//在此示例中,我们填充绑定到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服务循环。
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>();
// 循环通过可用特性。
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通知
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
// Characteristic notification
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic)
{
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
关闭客户端应用程序
一旦您的应用程序完成使用BLE设备,它应该调用close(),以便系统可以正确释放资源:
public void close()
{
if (mBluetoothGatt == null)
{
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
另外推荐几篇有关低功耗蓝牙开发的好文章:
蓝牙自动配对: