Android BLE 蓝牙学习总结(二):手机作为中央BluetoothGatt的实现

本文主要介绍了Android系统中如何实现蓝牙低功耗(BLE)的中央角色,包括创建中央的基本概念,如获取BluetoothManager、BluetoothAdapter,扫描并连接设备,以及数据的读写交互。文中详细阐述了连接成功后服务的发现过程,以及数据写入时的回调流程。此外,还提供了案例分析,涵盖权限设置、初始化蓝牙、扫描设备、建立连接和数据交互的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、创建中央基本概念
1.1、中央涉及的类有:
这里写图片描述
说明:为了拿到中央BluetoothGatt,需要经历以下过程:
1、先拿到BluetoothManager:bluetoothManager=(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
2、再拿到BluetoothAdapter:bluetoothAdapter=bluetoothManager.getAdapter();
3、开始扫描:bluetoothAdapter.startLeScan(BluetoothAdpater.LeScanCallback);
4、从LeScanCallback中得到BluetoothDevice:public void onLeScan(BluetoothDevice device,int rssi,byte[] scanRecord){……};
5、用BluetoothDevice得到BluetoothGatt:gatt=device.connectGatt(this,true,gattCallback);
6、接下来调用BluetoothGatt的方法,通过BluetoothGattCallback和周边的BluetoothServer进行交互

1.2、扫描以及读取与写入数据的相关概念:
监听扫描结果:
mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {}
};
device 搜索到的bye设备。
rssi 信号强度
scanRecord 远程设备广告记录的内容(蓝牙名称)
发起连接请求,获得中央。
mBluetoothGatt = device.connectGatt(mContext, false,mGattCallback);
第二个参数autoConnect 如果为false直接立即连接。
true 等待远程设备可用时(在范围内,。。)连接。并不是断开后重新连接。
第三个参数 Gatt callback 。
private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {};
连接成功后,发送 gatt服务发现请求。
//连接状态改变回调
onConnectionStateChange(BluetoothGatt gatt, int status, int newState){
if(newState == BluetoothProfile.STATE_CONNECTED){
//连接成功后,发送发现服务请求。
mBluetoothGatt.discoverServices();
}
}
//发现服务回调。
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if(status == BluetoothGatt.GATT_SUCCESS){
//发现成功后,则可以通过下面方法获取service 列表。
mBluetoothGatt.getServices();
}
}

1.3、中央与周边的数据交互过程总结(写入):
1、当点击事件调用该方法时BluetoothGatt.writeCharacteristic(characteristic),
a、系统异步回调onCharacteristicChanged()方法,
b、与此同时服务端:系统回调onCharacteristicWriteRequest()方法,通过该方法的参数value得到客户端发送过来的数据,在该回调方法中调用sendResponse()回复客户端响应成功,接着处理接受的数据,并通过BluetoothGattServer.notityCharacteristicChanged(device,characteristicRead,false)将回应的数据发送给客户端,该回应的数据就通过onCharacteristicChanged()方法的参数传递到客户

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值