BluetoothManager
蓝牙管理器,用于获取实例BluetoothAdapter并执行整体蓝牙管理.
方法
BluetoothAdapter
本地设备的蓝牙适配器,可用此执行基本的蓝牙任务,例如:
- 启动设备发现(discovery),查询配对设备列表
- 使用已知的MAC地址实例化蓝牙设备(BluetoothDevice)
创建蓝牙服务接口(BluetoothServerSocket)并运用listenUsingRfcommWithServiceRecord(String,
UUID)以侦听传入的连接请求 - 运用startLeScan(LeScanCallback)来进行BLE(低功耗蓝牙设备)的扫描
嵌套类
接口(BluetoothAdapter.LeScanCallback):提供BLE扫描结果的回传接口
参数
方法
标黑方法即为可能会用到的,单独说明:
- disable() 直接关闭蓝牙
- enable() 直接打开蓝牙
- getAddress() 获取本地蓝牙适配器的Mac地址
- getDefaultAdapter() 获取本地默认的蓝牙适配器
- getName() 获取本地蓝牙适配器的名称
- isEnabled() 获取蓝牙状态信息
- startLeScan(…) 开始搜索BLE
- stopLeScan(…) 停止搜索BLE
BluetoothDevice(扩展自对象)
表示远程的蓝牙设备
参数
方法
BluetoothAdapter.LeScanCallback (接口)
用于提供BLE扫描结果的回传接口
方法
onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
报告在startLeScan(BluetoothAdapter.LeScanCallback)扫描过程中发现的BLE设备
参数
Device:返回设备(BluetoothDevice)
Rssi:硬件报告远程设备的RSSI值
scanRecord:远程设备提供的通告帧内容
AndroidManifest.xml中:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
使用BLE函数的相关java中:
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothAdapter;
//以上为必须,以下为Google推荐在Android6.0及以上使用
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
主体函数
//系统蓝牙管理器
BluetoothManager A=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
//系统蓝牙适配器
BluetoothAdapter B=A.getAdapter();
//开始扫描
B. startLeScan(C);
//回传接口
BluetoothAdapter.LeScanCallback C=new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
//这里写扫描处理的代码
}
}
//停止扫描
B.stopLeScan();
在安卓6.0及以上,Google推荐使用以下代码:
//系统蓝牙管理器
BluetoothManager A=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
//系统蓝牙适配器
BluetoothAdapter B=A.getAdapter();
//BLE扫描
BluetoothLeScanner C=B.getBluetoothLeScanner();
//开始扫描
C.startScan(D)
//回传接口
ScanCallback D=new ScanCallback{
@Override
Public void onScanResult(int callbackType, ScanResult result){
super.onScanResult(callbackType,result);
//这里写扫描处理的代码
}
}
C.stopScan();
原文及文章图片:
链接: https://pan.baidu.com/s/1jeaslWN1bG58djYWfnYneQ 提取码: hjzt