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

deviceList.add(bluetoothDevice);

list.setAdapter(new MyAdapter(MainActivity.this, deviceList));

}

}

};

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

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

  1. Context上下文

  2. autoConnect是否自动重连(Boolean)

  3. BluetoothGattCallback 回调方法

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

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

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

BLE实战准备

==================================================================

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

真机调试


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

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

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

权限准备


1.在Manifest文件中添加

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

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

写两个简单的页面


扫描设备主界面

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:tools=“http://schemas.android.com/tools”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

android:orientation=“vertical”

tools:context=“com.example.blue_test.MainActivity”>>

<Button

android:id=“@+id/Search_device”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:text=“扫描设备”/>

<TextView

android:id=“@+id/Connection_Status”

android:layout_width=“match_parent”

android:layout_height=“wrap_content”

android:text=“连接状态:未连接”

android:gravity=“center”

android:textSize=“20dp”/>

<ListView

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:id=“@+id/list”

/>

实现效果:

在这里插入图片描述

扫描设备信息界面

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:app=“http://schemas.android.com/apk/r

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值