Android BLE开发: BLE Peripheral开发流程

2024-06-03 17:58

本文主要是介绍Android BLE开发: BLE Peripheral开发流程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Android从lolipop开始支持了BLE Peripheral开发。网上也有关于Framework的文章。真的关于应用开发的确不多,google官网也只给出了一个Central的Demo。之前做了一个BLE Peripheral的Demo,这里将Peripheral开发的一些流程简单整理一下。不多说,直接上代码。

初始化

//初始化BluetoothManager和BluetoothAdapter
if(mBluetoothManager == null)mBluetoothManager = (BluetoothManager) mActivity.getSystemService(Context.BLUETOOTH_SERVICE);if (mBluetoothManager != null && mBluetoothAdapter == null) {mBluetoothAdapter = mBluetoothManager.getAdapter();
}//打开蓝牙的套路
if ((mBluetoothAdapter == null) || (!mBluetoothAdapter.isEnabled())) {Toast.makeText(mActivity, R.string.bt_unavailable, Toast.LENGTH_SHORT).show();Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);mActivity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}

开始广播

//获取BluetoothLeAdvertiser,BLE发送BLE广播用的一个API
if (mBluetoothAdvertiser == null) {mBluetoothAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
}
//创建BluetoothGattServerCallback,
//MockServerCallBack这个类继承自BluetoothGattServerCallback
//后面会贴出MockServerCallBack这个类的代码
//BluetoothGattServerCallback这个回调类主要是一些BLE读写的接口
//关于BLE读写的操作都在这个Callback中完成
if (mBluetoothAdvertiser != null) {mMockServerCallBack = new MockServerCallBack(mActivity);//打开BluetoothGattServermGattServer = mBluetoothManager.openGattServer(mActivity, mMockServerCallBack);if(mGattServer == null){Log.d(TAG , "gatt is null");}try{mMockServerCallBack.setupServices(mGattServer);//创建BLE Adevertising并且广播mBluetoothAdvertiser.startAdvertising(createAdvSettings(true, 0), createFMPAdvertiseData(),mAdvCallback);}catch(InterruptedException e){Log.v(TAG, "Fail to setup BleService");}
}

创建Advertising

public static AdvertiseSettings createAdvSettings(boolean connectable, int timeoutMillis) {AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();//设置广播的模式,应该是跟功耗相关builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);builder.setConnectable(connectable);builder.setTimeout(timeoutMillis);builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);return builder.build();
}//设置一下FMP广播数据
public static AdvertiseData createFMPAdvertiseData() {AdvertiseData.Builder builder = new AdvertiseData.Builder();builder.setIncludeDeviceName(true);AdvertiseData adv = builder.build();return adv;
}//发送广播的回调,onStartSuccess/onStartFailure很明显的两个Callback
private AdvertiseCallback mAdvCallback = new AdvertiseCallback() {public void onStartSuccess(android.bluetooth.le.AdvertiseSettings settingsInEffect) {if (settingsInEffect != null) {Log.d(TAG, "onStartSuccess TxPowerLv="+ settingsInEffect.getTxPowerLevel()+ " mode=" + settingsInEffect.getMode()+ " timeout=" + settingsInEffect.getTimeout());} else {Log.d(TAG, "onStartSuccess, settingInEffect is null");}}public void onStartFailure(int errorCode) {Log.d(TAG, "onStartFailure errorCode=" + errorCode);};
};

BLE需要的BluetoothGattServerCallback

import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothGattService;
import android.util.Log;public class MockServerCallBack extends BluetoothGattServerCallback {private static final String TAG = "BleServer";private byte[] mAlertLevel = new byte[] {(byte) 0x00};private Activity mActivity;private HomePager mHomepager;private boolean mIsPushStatic = false;private BluetoothGattServer mGattServer;private BluetoothGattCharacteristic mDateChar;private BluetoothDevice btClient;private BluetoothGattCharacteristic mHeartRateChar;private BluetoothGattCharacteristic mTemperatureChar;private BluetoothGattCharacteristic mBatteryChar;private BluetoothGattCharacteristic mManufacturerNameChar;private BluetoothGattCharacteristic mModuleNumberChar;private BluetoothGattCharacteristic mSerialNumberChar;public void setupServices(BluetoothGattServer gattServer) throws InterruptedException{if (gattServer == null) {throw new IllegalArgumentException("gattServer is null");}mGattServer = gattServer;// 设置一个GattService以及BluetoothGattCharacteristic { //immediate alertBluetoothGattService ias = new BluetoothGattService( UUID.fromString(IMXUuid.SERVICE_IMMEDIATE_ALERT),BluetoothGattService.SERVICE_TYPE_PRIMARY);//alert level char.BluetoothGattCharacteristic alc = new BluetoothGattCharacteristic(UUID.fromString(IMXUuid.CHAR_ALERT_LEVEL),BluetoothGattCharacteristic.PROPERTY_READ |BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_NOTIFY ,BluetoothGattCharacteristic.PERMISSION_READ |BluetoothGattCharacteristic.PERMISSION_WRITE);alc.setValue("");ias.addCharacteristic(alc);if(mGattServer!=null && ias!=null)mGattServer.addService(ias);}}//当添加一个GattService成功后会回调改接口。public void onServiceAdded(int status, BluetoothGattService service) {if (status == BluetoothGatt.GATT_SUCCESS) {Log.d(TAG, "onServiceAdded status=GATT_SUCCESS service=" + service.getUuid().toString());} else {Log.d(TAG, "onServiceAdded status!=GATT_SUCCESS");}}//BLE连接状态改变后回调的接口public void onConnectionStateChange(android.bluetooth.BluetoothDevice device, int status,int newState) {Log.d(TAG, "onConnectionStateChange status=" + status + "->" + newState);}//当有客户端来读数据时回调的接口public void onCharacteristicReadRequest(android.bluetooth.BluetoothDevice device,int requestId, int offset, BluetoothGattCharacteristic characteristic) {Log.d(TAG, "onCharacteristicReadRequest requestId=" + requestId + " offset=" + offset);mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset,characteristic.getValue());}//当有客户端来写数据时回调的接口@Overridepublic void onCharacteristicWriteRequest(android.bluetooth.BluetoothDevice device,int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite,boolean responseNeeded, int offset, byte[] value) {mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, null);}//当有客户端来写Descriptor时回调的接口@Overridepublic void onDescriptorWriteRequest (BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {btClient = device;Log.d(TAG, "onDescriptorWriteRequest");// now tell the connected device that this was all successfullmGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);}
}

至此,BLE Peripheral发送广播所需要的工作都完成了,并且当有Central设备读写该Peripheral设备时候也能通过BluetoothGattServerCallback回调到。

停止广播

//关闭BluetoothLeAdvertiser,BluetoothAdapter,BluetoothGattServer 
if (mBluetoothAdvertiser != null) {mBluetoothAdvertiser.stopAdvertising(mAdvCallback);mBluetoothAdvertiser = null;
}if(mBluetoothAdapter != null){mBluetoothAdapter = null;
}if (mGattServer != null) {mGattServer.clearServices();mGattServer.close();
}       

这样,Android设备就停止了BLE的广播,外部的Central设备就搜索不到该设备并且连接上它了。
BLE Peripheral的API乍一看有些多,其实仔细理一理非常简单,工作重点在于那个Callback的编写。

这篇关于Android BLE开发: BLE Peripheral开发流程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1027704

相关文章

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S

SpringBoot开发中十大常见陷阱深度解析与避坑指南

《SpringBoot开发中十大常见陷阱深度解析与避坑指南》在SpringBoot的开发过程中,即使是经验丰富的开发者也难免会遇到各种棘手的问题,本文将针对SpringBoot开发中十大常见的“坑... 目录引言一、配置总出错?是不是同时用了.properties和.yml?二、换个位置配置就失效?搞清楚加

Android DataBinding 与 MVVM使用详解

《AndroidDataBinding与MVVM使用详解》本文介绍AndroidDataBinding库,其通过绑定UI组件与数据源实现自动更新,支持双向绑定和逻辑运算,减少模板代码,结合MV... 目录一、DataBinding 核心概念二、配置与基础使用1. 启用 DataBinding 2. 基础布局

Python中对FFmpeg封装开发库FFmpy详解

《Python中对FFmpeg封装开发库FFmpy详解》:本文主要介绍Python中对FFmpeg封装开发库FFmpy,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、FFmpy简介与安装1.1 FFmpy概述1.2 安装方法二、FFmpy核心类与方法2.1 FF

Android ViewBinding使用流程

《AndroidViewBinding使用流程》AndroidViewBinding是Jetpack组件,替代findViewById,提供类型安全、空安全和编译时检查,代码简洁且性能优化,相比Da... 目录一、核心概念二、ViewBinding优点三、使用流程1. 启用 ViewBinding (模块级

基于Python开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c