一、BLE概述
Android4.3以上加入了BLE——低功耗蓝牙。
使用低功耗蓝牙可以包括多个Profile,一个Profile中有多个Service,一个Service中有多个Characteristic,一个Characteristic中包括一个value和多个Descriptor。
二、BLE的使用
1.权限
和经典蓝牙一样,应用使用蓝牙,需要声明BLUETOOTH权限,如果需要扫描设备或者操作蓝牙设置,则还需要BLUETOOTH_ADMIN权限:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
required为true时,则应用只能在支持BLE的Android设备上安装运行;required为false时,Android设备均可正常安装运行,需要在代码运行时判断设备是否支持BLE:
// 判断当前手机是否支持BLE
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish(); }
2.使用步骤
2.1 初始化 BluetoothAdapter,用来判断设备是否支持蓝牙并打开蓝牙
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
finalBluetoothManager bluetoothManager =
(BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter= bluetoothManager.getAdapter();
// 判断是否支持蓝牙
if(mBluetoothAdapter==null) {
return false;
}
//打开蓝牙
if(!mBluetoothAdapter.isEnabled()) {