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

相关文章

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

Python使用smtplib库开发一个邮件自动发送工具

《Python使用smtplib库开发一个邮件自动发送工具》在现代软件开发中,自动化邮件发送是一个非常实用的功能,无论是系统通知、营销邮件、还是日常工作报告,Python的smtplib库都能帮助我们... 目录代码实现与知识点解析1. 导入必要的库2. 配置邮件服务器参数3. 创建邮件发送类4. 实现邮件

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

基于Python开发一个有趣的工作时长计算器

《基于Python开发一个有趣的工作时长计算器》随着远程办公和弹性工作制的兴起,个人及团队对于工作时长的准确统计需求日益增长,本文将使用Python和PyQt5打造一个工作时长计算器,感兴趣的小伙伴可... 目录概述功能介绍界面展示php软件使用步骤说明代码详解1.窗口初始化与布局2.工作时长计算核心逻辑3

python web 开发之Flask中间件与请求处理钩子的最佳实践

《pythonweb开发之Flask中间件与请求处理钩子的最佳实践》Flask作为轻量级Web框架,提供了灵活的请求处理机制,中间件和请求钩子允许开发者在请求处理的不同阶段插入自定义逻辑,实现诸如... 目录Flask中间件与请求处理钩子完全指南1. 引言2. 请求处理生命周期概述3. 请求钩子详解3.1

spring-gateway filters添加自定义过滤器实现流程分析(可插拔)

《spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔)》:本文主要介绍spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔),本文通过实例图... 目录需求背景需求拆解设计流程及作用域逻辑处理代码逻辑需求背景公司要求,通过公司网络代理访问的请求需要做请

如何基于Python开发一个微信自动化工具

《如何基于Python开发一个微信自动化工具》在当今数字化办公场景中,自动化工具已成为提升工作效率的利器,本文将深入剖析一个基于Python的微信自动化工具开发全过程,有需要的小伙伴可以了解下... 目录概述功能全景1. 核心功能模块2. 特色功能效果展示1. 主界面概览2. 定时任务配置3. 操作日志演示