1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 安卓基于BLE的蓝牙开发入门

安卓基于BLE的蓝牙开发入门

时间:2018-10-01 16:57:23

相关推荐

安卓基于BLE的蓝牙开发入门

BLE蓝牙开发简单入门

BLE背景介绍引言BLE简介Gatt协议以及必备知识蓝牙开发涉及的API介绍BLE实战准备真机调试权限准备写两个简单的页面扫描设备主界面扫描设备信息界面实现扫描并返回检测到的设备连接设备的数据读写总结

BLE背景介绍

引言

如今,蓝牙的使用在生活中是越来越常见了,各色各样的运动手环、体脂称以及无线耳机都用到了蓝牙功能,如今火热的keep、小米运动等app也是通过简单的蓝牙连接与运动手环进行交互,因此通过本博客对安卓的蓝牙开发部分做一个简单的入门

BLE简介

蓝牙低能耗(Bluetooth Low Energy,或称Bluetooth LE、BLE,旧商标Bluetooth Smart)也称低功耗蓝牙,是蓝牙技术联盟设计和销售的一种个人局域网技术,旨在用于医疗保健、运动健身、信标、安防、家庭娱乐等领域的新兴应用。相较经典蓝牙,低功耗蓝牙旨在保持同等通信范围的同时显著降低功耗和成本。可以说BLE的出现大大的推进了蓝牙的使用。

Gatt协议以及必备知识

首先,我们所探讨的低功耗蓝牙(BLE)连接都是建立在 GATT (Generic Attribute Profile) 协议之上的,GATT是蓝牙传递数据的一个通用规范

我们来了解一些与蓝牙有关的关键词**

UUID:可以理解为用于区分身份的唯一标识符

Service:对于每一个Service以及每一个characteristic都有着自己唯一的UUID

Service是蓝牙设备中的服务,一个设备可以拥有多个服务,举例子:小米手环具备好几个服务,比如手环的基本信息、电量信息、心率检测、步数记录等

characteristic:一个服务中可以存在着多个characteristic,可以将这些characteristic看做一个个独立的数据项,同样用小米手环举例子,在手环的Generic Access模块里存在着多个characteristic如,Device Name、Appearance、Peripheral Preferred Connection Parameter,如果你要向小米手环发送一个心率检测的通知,那么你就需要找到对应的characteristic的UUID,对这个characteristic进行通信

下图是蓝牙调试工具的界面,通过它应该可以对上述所说的几个关键字有更深刻的认识

根据下面的官方图片我们可以看到

Characteristic中含有多个属性,如value、properties、Descriptor,这里做简单的说明

value:特征数据值,比如心率值或者步数

Descriptor:对数据的说明信息,比如数据的单位等

Properties:定义Value如何使用以及Descriptor如何访问

蓝牙开发涉及的API介绍

有了以上的知识铺垫我们对蓝牙已经有了一个大致的认识,那么现在我们对安卓开发中连接设备以及读写数据的API做一个认识,代码在这里不是重点,之后的章节会重点讲述,

这里主要是了解API之间的关系以及作用

BluetoothManager:蓝牙管理,用于得到BluetoothAdapter

//调用系统服务获取一个BluetoothManager实例BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);bluetoothAdapter = bluetoothManager.getAdapter();

BluetoothAdapter:通过 BluetoothManager 获取,扫描蓝牙设备,回调方法中会将扫描到的蓝牙设备添加进BluetoothDevice中

bluetoothAdapter.startLeScan(callback)

BluetoothDevice:代表了连接的蓝牙设备,获取一些有关它的信息,如设备名称,地址等

//回调//扫描回调public BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback(){@Overridepublic void onLeScan(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {//重复过滤方法,列表中包含不该设备才加入列表中,并刷新列表if (!deviceList.contains(bluetoothDevice)) {//将设备加入列表数据中deviceList.add(bluetoothDevice);list.setAdapter(new MyAdapter(MainActivity.this, deviceList));}}};

此时我们已经通过上述三个api实现了扫描并生成设备列表的过程,那么理所当然,我们要对列表中的设备进行连接,那么我们就需要用到BluetoothDevice中的connectGatt方法,这个方法与对应的设备连接后可以得到一个BluetoothGatt对象

这里说明connectGatt方法包含三个参数

Context上下文autoConnect是否自动重连(Boolean)BluetoothGattCallback 回调方法

BluetoothGatt:实现蓝牙的基本功能,可以重新连接蓝牙设备,发现蓝牙设备的 Service。

BluetoothGattCallback:里面有许多方法,对应着各种操作的回调(比如读写操作以及获取服务),我们按照需要实现即可

BluetoothGattService:通过BluetoothGatt可以得到,对应上文提到的Service,通过这个类我们可以得到所需要的characteristic

BLE实战准备

了解了以上内容以后,我们就做一个简单的安卓应用,连接上测试用的小米手环。

真机调试

安卓的蓝牙开发必然要用到真机调试,这里就简单的说明一下,如果真机连接不上可以在网上查找对应的解决办法

1.进入手机的(更多设置中)开发者选项(这里以小米为例,进入设置,在我的设备中找到全部参数,连点MIUI版本处看到下方提示进入开发者选项即可),打开USB调试以及USB安装即可

2.打开andorid studio,将数据线连接上手机,就进入了真机调试。

权限准备

1.在Manifest文件中添加

<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

这里需要添加以上权限,否则会导致闪退

2.如果程序正常运行,但是扫描不到任何的设备,打开手机,进入手机权限管理,给安装的app定位权限设置为允许,同时保证手机中的位置信息是打开的,这步非常重要,旧版本的安卓系统可以略过,本机为andorid 10版本,如果不操作这步将不能看到任何设备

写两个简单的页面

扫描设备主界面

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="com.example.blue_test.MainActivity">><Buttonandroid:id="@+id/Search_device"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="扫描设备"/><TextViewandroid:id="@+id/Connection_Status"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="连接状态:未连接"android:gravity="center"android:textSize="20dp"/><ListViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:id="@+id/list"/></LinearLayout>

实现效果:

扫描设备信息界面

<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayoutxmlns:android="/apk/res/android"xmlns:app="/apk/res-auto"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:id="@+id/bluetoothicon"android:layout_width="37dp"android:layout_height="50dp"android:background="@drawable/ic_launcher_background"android:src="@android:drawable/stat_sys_data_bluetooth"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /><TextViewandroid:id="@+id/bluetoothname"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="16dp"android:text="name"android:textColor="#000000"android:textSize="19dp"app:layout_constraintStart_toEndOf="@+id/bluetoothicon"app:layout_constraintTop_toTopOf="parent" /><TextViewandroid:id="@+id/uuid"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginStart="16dp"android:layout_marginTop="4dp"android:text="uuid"android:textSize="15dp"app:layout_constraintStart_toEndOf="@+id/bluetoothicon"app:layout_constraintTop_toBottomOf="@+id/bluetoothname" /><TextViewandroid:id="@+id/status"android:layout_width="0dp"android:layout_height="13dp"android:text=""android:textColor="#ff0000"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintHorizontal_bias="0.0"app:layout_constraintStart_toEndOf="@+id/bluetoothname"app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>

实现扫描并返回检测到的设备

创建变量

重新回顾一下之前提到的api

private Button Search_device;//扫描设备按钮private TextView connection_Status; //连接状态TextViewprivate ListView list; //设备listBluetoothAdapter bluetoothAdapter; //蓝牙适配器BluetoothGatt bluetoothGatt; //连接设备后的操作类List<BluetoothDevice> deviceList = new ArrayList<>(); //存储扫描到的所有设备List<String> serviceslist = new ArrayList<String>(); //存储连接设备的所有服务的uuidBluetoothDevice bluetoothDevice; //某个设备BluetoothGattService bluetoothGattServices; //对应着上文提到的服务BluetoothGattCharacteristic characteristic_zd, characteristic_jb; //服务下的特征(characteristic)

onCeate方法

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();//蓝牙管理类,通过getSystemService(BLUETOOTH_SERVICE)的方法获取实例BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);//通过蓝牙管理实例获取适配器,然后通过扫描方法(scan)获取设备(device)bluetoothAdapter = bluetoothManager.getAdapter();}

initView方法代码如下,实现可连接蓝牙设备列表的点击监听

private void initView() {Search_device = (Button) findViewById(R.id.search_device);list = (ListView) findViewById(R.id.list);connection_Status = (TextView) findViewById(R.id.connection_status);Search_device.setOnClickListener(this);//item 监听事件list.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {bluetoothDevice = deviceList.get(i);//根据监听器返回的位置,得到扫描设备列表中对应的设备//上文提到的,通过bluetoothDevice的connectGatt方法连接设备并返回BluetoothGatt实例bluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this, false, gattcallback);connection_Status.setText("正在连接" + bluetoothDevice.getName() + "中...");}});}

上文有提到,通过bluetoothDevice的connectGatt方法连接设备返回一个BluetoothGatt实例,如果还有印象的读者应该记得,这里的connectGatt方法需要实现三个参数,

上下文,这里是MainActivity.this自动重连,设置为false代表不自动重连,true为自动重连BluetoothGattCallback类(回调),我们这里需要实现回调类的里面的方法,之后我们再看BluetoothGattCallback类的实现

点击扫描设备的监听

public void onClick(View view) {switch (view.getId()) {case R.id.search_device://开始扫描前开启蓝牙,通过intent发起一个打开蓝牙的通知Intent Bluetooth_open_request= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);startActivityForResult(Bluetooth_open_request, 0);//开启一个扫描线程Thread scanThread = new Thread(new Runnable() {@Overridepublic void run() {deviceList.clear(); //把之前存储的设备信息清空bluetoothAdapter.startLeScan(callback); //调用适配器方法扫描}});scanThread.start();connection_Status.setText("正在扫描");break;}}

这里的callback是一个相当于扫描到设备以后,会调用我们实现的callback中的方法,这里我们实现创建一个类实现LeScanCallback的onLeScan方法,使得设备扫描以后将新设备添加进deviceList中。

这里的callback需要和上面的BluetoothGattCallback区分开BluetoothGattCallback是与某个设备连接以后的回调,而callback是扫描设备以后的回调并没有连接设备

//扫描回调public BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback(){@Overridepublic void onLeScan(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {//使用contains方法查看当前扫描到的设备是否已经在列表中,如果不在就添加if (!deviceList.contains(bluetoothDevice)) {//将设备加入列表中,通过适配器显示deviceList.add(bluetoothDevice);list.setAdapter(new BsAdapter(MainActivity.this, deviceList));}}};

这里的BsAdapter是继承BaseAdapter实现的一个适配器类

使用自定义适配器只需要写一个类继承BaseAdpter并实现4个抽象方法即可,这里不过多探讨,自定义适配器使用起来并不困难,如果需要可以自行查阅相关资料

public class BsAdapter extends BaseAdapter {public List<BluetoothDevice> bluetooth_Device_list;private LayoutInflater Lflater;public BsAdapter(Context context , List<BluetoothDevice> list){bluetooth_Device_list = list;Lflater = LayoutInflater.from(context);}//获取传入的数组大小@Overridepublic int getCount() {return bluetooth_Device_list.size();}//获取第N条数据@Overridepublic Object getItem(int i) {return bluetooth_Device_list.get(i);}//获取item id@Overridepublic long getItemId(int i) {return i;}@Overridepublic View getView(int i, View view, ViewGroup viewGroup) {ViewHolder viewHolder = new ViewHolder();if(view == null){view = Lflater.inflate(R.layout.devices_item , null);viewHolder.name = (TextView) view.findViewById(R.id.bluetooth_name);viewHolder.uuid = (TextView) view.findViewById(R.id.uuid);viewHolder.status = (TextView) view.findViewById(R.id.status);view.setTag(viewHolder);}else{viewHolder = (ViewHolder) view.getTag();}BluetoothDevice bd = bluetooth_Device_list.get(i);viewHolder.name.setText(bd.getName()); //从BluetoothDevice中得到设备的名称viewHolder.uuid.setText(bd.getAddress());//从BluetoothDevice中得到设备的MAC地址return view;}//封装一个item的数据class ViewHolder{private TextView name , uuid , status;}}

连接设备的数据读写

实现BluetoothGattCallback回调

先来介绍需要实现的方法有哪些

onConnectionStateChange() 连接状态改变的回调方法onServicesDiscovered()搜索到设备的服务时的回调方法onCharacteristicRead()对characteristic读操作的回调方法onCharacteristicWrite()对characteristic写操作的回调方法

先来看onConnectionStateChange方法

@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, final int newState) {super.onConnectionStateChange(gatt, status, newState);runOnUiThread(new Runnable() {@Overridepublic void run() {String status;//根据返回的状态更新设置switch (newState) {case BluetoothGatt.STATE_CONNECTED:connection_Status.setText("已连接");//因为已经连接所以停止调用适配器的LeScan方法bluetoothAdapter.stopLeScan(callback);//获取连接设备的服务bluetoothGatt.discoverServices();break;case BluetoothGatt.STATE_CONNECTING:connection_Status.setText("正在连接");break;case BluetoothGatt.STATE_DISCONNECTED:connection_Status.setText("已断开");break;}}});}

onServicesDiscovered方法 这里遍历所有的服务以及服务下的特征,并输出其中的uuid

@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {super.onServicesDiscovered(gatt, status);//寻找到服务时if (status == bluetoothGatt.GATT_SUCCESS) {//得到连接设备的所有服务final List<BluetoothGattService> services = bluetoothGatt.getServices();runOnUiThread(new Runnable() {@Overridepublic void run() {//遍历所有服务for (final BluetoothGattService bluetoothGattService : services) {bluetoothGattServices = bluetoothGattService;Log.i(TAG, "onServicesDiscovered: " + bluetoothGattService.getUuid());//输出服务对应的uuid//将当前遍历的服务的characteristic放入list中List<BluetoothGattCharacteristic> charc = bluetoothGattService.getCharacteristics();//遍历当前服务下的所有characteristicfor (BluetoothGattCharacteristic charac : charc) {Log.i(TAG, "run: " + charac.getUuid());//输出当前遍历到的characteristic的特征值if (charac.getUuid().toString().equals("对应的UUID"))//放入对应的特征的uuid{//此处为确定某个特征之后对应的操作,下面同理bluetoothGatt.readCharacteristic(charac);//这里代表对目标特征进行读操作,当与连接设备进行读操作的时候回调方法}else if (charac.getUuid().toString().equals("对应的UUID")){}else if (charac.getUuid().toString().equals("对应的UUID")) {}}serviceslist.add(bluetoothGattService.getUuid().toString());}}});}}

看看控制台输出结果,这里就是小米手环4的所有服务UUID以及服务下的characteristic的UUID

这里我们并不知道每一个服务对应的手环的什么功能,哪一个characteristic中存储了我们所需要的数据,我们都知道小米运动app在进入跑步状态时,只要手环处于连接状态就会自动的检测你的心率,与小米运动app共享数据,这里实际上就是通过其中某个uuid向手环发送了数据,手环收到消息以后开启心率检测功能并持续返回心率数据,因此这里只能模拟过程。

与连接设备读操作的回调方法

@Overridepublic void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {super.onCharacteristicRead(gatt, characteristic, status);if (status == bluetoothGatt.GATT_SUCCESS) {//这里读取一个目标特征的特征值final int sum = characteristic.getValue()[0];//输出Log.e(TAG, "onCharacteristicRead: " + characteristic.getValue()[0]);}}

这里读取到了遍历到的第一个特征的特征值value[0]的数据,每一个特征下面都有一个value数组存储特征值

写操作的回调方法

使用bluetoothGatt.writeCharacteristic(charac)即可向设备发送数据,发送数据都是通过characteristic,发送数据的步骤通常为找到对应的目标characteristic的uuid,向characteristic中setvalue(),调用方法发送数据,等待下列回调方法调用

@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {super.onCharacteristicWrite(gatt, characteristic, status);//写操作后的回调操作Log.i(TAG, "onCharacteristicWrite: "+"写入数据");}

我们队uuid为"00002a06-0000-1000-8000-00805f9b34fb"的特征发送一个数据

if(charac.getUuid().toString().equals("00002a06-0000-1000-8000-00805f9b34fb")) {//bluetoothGatt.readCharacteristic(charac);byte[] value = {(byte) 0x02};charac.setValue(HexUtil.encodeHexStr(value));bluetoothGatt.writeCharacteristic(charac);}

可以看到下图的结果,onCharacteristicWrite中的status返回写入结果的说明

这里的0为BluetoothGatt.GATT_SUCCESS,代表成功

记步功能实时更新需要做的事

这里只是提及,因为不知道记步对应的UUID,网上也只有小米手环2的UUID说明,因此不便于验证,但是不妨碍我们正常学习。

手环记录步数在移动时必然是不断改变的,如果想要实时的更新步数的话,就需要作以下的操作

这里模拟当步数对应的特征中的值发生改变,更新新数据。

//这里可以看做对一个特征值改变的回调@Overridepublic void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {super.onCharacteristicChanged(gatt, characteristic);final byte[] values = characteristic.getValue();//得到返回的新步数runOnUiThread(new Runnable() {@Overridepublic void run() {//模拟更新界面显示新步数}});}

总结

以上就是安卓基于BLE的蓝牙开发入门的全部内容,实际上由于UUID不明,同时手环更新换代以后的数据交互模式可能有所改变,因此读写部分只是做了控制台的简单输入输出测验,但是我相信看完这篇文章以后对安卓端的蓝牙BLE模块肯定会有较为清晰的理解,下图是程序的运行截图,最后只是简单的实现了扫描连接的界面化,并没有添加数据的读写。

蓝牙开发中的奇怪问题确实比较多,因此需要耐心查阅资料,排查可能的问题,如果文章内容有不正确的地方欢迎指正。下面附带程序截图

作者:聂历凡

原文地址

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。