安卓端调用蓝牙BLE实现扫描低功耗蓝牙设备

  • 相关类详解

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:远程设备提供的通告帧内容


  • 使用BLE的方法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值