Android BLE简介
蓝牙低能耗(Bluetooth Low Energy,或称Bluetooth LE、BLE,旧商标Bluetooth Smart)也称低功耗蓝牙,是蓝牙技术联盟设计和销售的一种个人局域网技术,旨在用于医疗保健、运动健身、信标、安防、家庭娱乐等领域的新兴应用。相较经典蓝牙,低功耗蓝牙旨在保持同等通信范围的同时显著降低功耗和成本。。
流程
扫描
- startDiscovery:扫传统蓝牙
java.lang.Object
↳ android.bluetooth.BluetoothAdapter
public boolean startDiscovery()
Returns
boolean true on success, false on error
Added in API level 5
Requires Manifest.permission.BLUETOOTH_ADMIN
- startLeScan:扫低功耗蓝牙
java.lang.Object
↳ android.bluetooth.BluetoothAdapter
public boolean startLeScan(UUID[] serviceUuids,
BluetoothAdapter.LeScanCallback callback)
Returns
boolean true, if the scan was started successfully
Added in API level 18
Deprecated in API level 21
This method was deprecated in API level 21.
use BluetoothLeScanner#startScan(List, ScanSettings, ScanCallback) instead.
Requires Manifest.permission.BLUETOOTH_ADMIN
- startScan
java.lang.Object
↳ android.bluetooth.le.BluetoothLeScanner
public void startScan (List<ScanFilter> filters,
ScanSettings settings,
ScanCallback callback)
Added in API level 21
An app must hold ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission in order to get results.
Requires Manifest.permission.BLUETOOTH_ADMIN
If you are targeting SDK version 21+, User should enable location in settings for BLE to work.
绑定/配对
- createBond
java.lang.Object
↳ android.bluetooth.BluetoothDevice
public boolean createBond ()
Returns
boolean false on immediate error, true if bonding will begin
Added in API level 19
Start the bonding (pairing) process with the remote device.
This is an asynchronous call, it will return immediately.
Requires Manifest.permission.BLUETOOTH_ADMIN
- setPin
java.lang.Object
↳ android.bluetooth.BluetoothDevice
public boolean setPin (byte[] pin)
Returns
boolean true pin has been set false for error
Added in API level 19
Set the pin during pairing
Requires Manifest.permission.BLUETOOTH_ADMIN.
连接
- connectGatt
java.lang.Object
↳ android.bluetooth.BluetoothDevice
public BluetoothGatt connectGatt (Context context,
boolean autoConnect,
BluetoothGattCallback callback)
Added in API level 18
- BluetoothGattCallback
java.lang.Object
↳ android.bluetooth.BluetoothGattCallback
public void onCharacteristicChanged (BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic)
Callback triggered as a result of a remote characteristic notification.
public void onCharacteristicRead (BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status)
Callback reporting the result of a characteristic read operation.
public void onCharacteristicWrite (BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status)
Callback indicating the result of a characteristic write operation.
Added in API level 18