Android 开发 BLE 用第三方库是总是出现一些问题,最后还是硬着头皮改回原生 API。
首先看官方文档:https://developer.android.com/guide/topics/connectivity/bluetooth-le
安卓4.3(API 18)为BLE的核心功能提供平台支持和API,App可以利用它来发现设备、查询服务和读写特性。相比传统的蓝牙,BLE更显著的特点是低功耗。这一优点使android App可以与具有低功耗要求的BLE设备通信,如近距离传感器、心脏速率监视器、健身设备等。
以下是Android设备与BLE设备交互时的角色和责任:
为了方便理解,想象你有一个 Android 手机和一个用于活动跟踪 BLE 设备,手机支持中央角色,活动跟踪器支持外围(为了建立 BLE 连接你需要注意两件事,只支持外围设备的两方或者只支持中央设备的两方不能互相通信)。
当手机和运动追踪器建立连接后,他们开始向另一方传输 GATT 数据。哪一方作为服务器取决于他们传输数据的种类。例如,如果运动追踪器想向手机报告传感器数据,运动追踪器是服务端。如果运动追踪器更新来自手机的数据,手机会作为服务端。
为了在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的可用性。
// 使用此检查确定 BLE 是否支持在设备上,然后你可以有选择性禁用 BLE 相关的功能
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
注意: BLE 通常与位置相关联。为了在没有筛选器的情况下使用 BluetoothLeScanner ,您必须通过在应用程序的清单文件中声明
ACCESS_COARSE_LOCATION
或ACCESS_FINE_LOCATION
权限来请求用户的权限。如果没有这些权限, 扫描将不会返回任何结果。
ACCESS_COARSE_LOCATION
或者 ACCESS_FINE_LOCATION
权限是使用 LoactionManger
方法所必须依靠的。
例如,如果你的应用程序仅仅使用基于网络的位置提供者,你需要声明 ACCESS_COARSE_LOCATION
权限。更高精度的 GPS
需要 ACCESS_FINE_LOCATION
权限。注意声明 ACCESS_FINE_LOCATION
权限已经包含了 ACCESS_COARSE_LOCATION
。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
或者更精确定位
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
你的 app 能与 BLE 通信之前,你需要确认设备是否支持 BLE,如果支持,确认已经启用。注意如果<uses-feature.../>
设置为 false
,这个检查才是必需的。
如果不支持BLE,那么你应该适当地禁用部分BLE功能。如果支持BLE但被禁用,你可以无需离开应用程序而要求用户启动蓝牙。使用BluetoothAdapter两步完成该设置。
所有的蓝牙活动都需要蓝牙适配器。BluetoothAdapter
代表设备本身的蓝牙适配器(蓝牙无线)。整个系统只有一个蓝牙适配器,而且你的 app
使用它与系统交互。下面的代码片段显示了如何得到适配器。注意该方法使用 getSystemService 返回 BluetoothManager,然后将其用于获取适配器的一个实例。Android 4.3 (API 18) 引入 BluetoothManager
。
private BluetoothAdapter mBluetoothAdapter;
...
// 初始化蓝牙适配器
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
false
,蓝牙被禁用。下面的代码检查蓝牙是否开启,如果没有开启,将显示错误提示用户去设置开启蓝牙。
// 确保蓝牙在设备上可以开启
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
为了发现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() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
...
}
...
}
如果你只想扫描指定类型的外围设备,可以改为调用 startLeScan(UUID[], BluetoothAdapter.LeScanCallback) ,需要提供你的 app 支持的 GATT services 的 UUID 对象数组。
作为BLE扫描结果的接口,下面是BluetoothAdapter.LeScanCallback的实现。
private LeDeviceListAdapter mLeDeviceListAdapter;
...
// 扫描回调
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();
}
});
}
};
注意:只能扫描 BLE 设备或者扫描传统蓝牙设备,不能同时扫描 BLE 和传统蓝牙设备。
与一个BLE设备交互的第一步就是连接它——更具体的,连接到BLE设备上的GATT服务端。为了连接到BLE设备上的GATT服务端,需要使用connectGatt( )方法。这个方法需要三个参数:一个Context对象,自动连接(boolean值,表示只要BLE设备可用是否自动连接到它),和BluetoothGattCallback调用。
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
连接到 GATT 服务端时,由 BLE 设备做主机,并返回一个 BluetoothGatt 实例,然后你可以使用这个实例来进行 GATT 客户端操作。请求方(Android app)是GATT客户端。BluetoothGattCallback 用于传递结果给用户,例如连接状态,以及任何进一步GATT客户端操作。
在这个例子中,这个BLE APP提供了一个activity(DeviceControlActivity)来连接,显示数据,显示该设备支持的GATT services和characteristics。根据用户的输入,这个activity与BluetoothLeService通信,通过Android BLE API实现与BLE设备交互。
//通过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() {
@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
// 发现新服务端
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 & x01) != 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));
}
}
};
你的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);
}
...
}
...
}
当设备上的特性改变时会通知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);
}
当你的app完成BLE设备的使用后,应该调用close(),系统可以合理释放占用资源。
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
新建 API 18: Android 4.3 (Jelly Bean) 的 Android Studio 项目。
AndroidStudio.png
AndroidManifest.xml
文件中声明蓝牙相关权限:
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
build.gradle (Project: XXX)
添加:
allprojects {
repositories {
google()
jcenter()
maven { url "https://jitpack.io" } # 只添加这一行
}
}
build.gradle (Module: app)
添加:
dependencies {
...
# 添加下面两行
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.38' # RecyclerView辅助
implementation 'me.yokeyword:fragmentation:1.3.3' # 单 Activity 多 fragment
}
// 判断是否需要向用户解释为什么需要申请该权限
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
Toast.makeText(this, "自Android 6.0开始需要打开位置权限才可以搜索到Ble设备", Toast.LENGTH_SHORT).show();
}
// 请求权限
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_CODE_ACCESS_COARSE_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_ACCESS_COARSE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户允许改权限,0表示允许,-1表示拒绝 PERMISSION_GRANTED = 0, PERMISSION_DENIED = -1
// 这里进行授权被允许的处理
Log.d(TAG, "onRequestPermissionsResult: PERMISSION_GRANTED");
} else {
// 这里进行权限被拒绝的处理
Toast.makeText(this, "XXX无法访问蓝牙,请打开XXX的位置权限。", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
if (!isLocationEnable(this)) {
setLocationService();
}
}
/**
* Location service if enable
*
* @param context
* @return location is enable if return true, otherwise disable.
*/
public static boolean isLocationEnable(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean networkProvider = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean gpsProvider = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return networkProvider || gpsProvider;
}
private void setLocationService() {
Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
this.startActivityForResult(locationIntent, REQUEST_CODE_LOCATION_SETTINGS);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_LOCATION_SETTINGS) {
if (isLocationEnable(this)) {
// 定位已打开的处理
Log.d(TAG, "onActivityResult: REQUEST_CODE_LOCATION_SETTINGS");
} else {
// 定位依然没有打开的处理
Toast.makeText(this, "XXX需要打开定位功能才能使用低功耗蓝牙", Toast.LENGTH_SHORT).show();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
新建 Server