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

本文详细介绍了如何在Android设备上设置开发者选项,启用USB调试,进行真机调试,以及在Manifest文件中添加权限。还涉及设备扫描、权限管理、BluetoothAPI的使用,包括LeScanCallback和BluetoothGattCallback回调方法。此外,还提供了Android学习资源链接,强调了坚持学习的重要性。
摘要由CSDN通过智能技术生成

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/res-auto”

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

android:layout_width=“match_parent”

android:layout_height=“match_parent”>

<ImageView

android: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” />

<TextView

android: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” />

<TextView

android: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” />

<TextView

android: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; //连接状态TextView

private ListView list; //设备list

BluetoothAdapter bluetoothAdapter; //蓝牙适配器

BluetoothGatt bluetoothGatt; //连接设备后的操作类

List deviceList = new ArrayList<>(); //存储扫描到的所有设备

List serviceslist = new ArrayList(); //存储连接设备的所有服务的uuid

BluetoothDevice bluetoothDevice; //某个设备

BluetoothGattService bluetoothGattServices; //对应着上文提到的服务

BluetoothGattCharacteristic characteristic_zd, characteristic_jb; //服务下的特征(characteristic)

onCeate方法

@Override

protected 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() {

@Override

public 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方法需要实现三个参数,

  1. 上下文,这里是MainActivity.this

  2. 自动重连,设置为false代表不自动重连,true为自动重连

  3. 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() {

@Override

public 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()

{

@Override

public 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 bluetooth_Device_list;

private LayoutInflater Lflater;

public BsAdapter(Context context , List list){

bluetooth_Device_list = list;

Lflater = LayoutInflater.from(context);

}

//获取传入的数组大小

@Override

public int getCount() {

return bluetooth_Device_list.size();

}

//获取第N条数据

@Override

public Object getItem(int i) {

return bluetooth_Device_list.get(i);

}

//获取item id

@Override

public long getItemId(int i) {

return i;

}

@Override

public 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方法

@Override

public void onConnectionStateChange(BluetoothGatt gatt, int status, final int newState) {

super.onConnectionStateChange(gatt, status, newState);

runOnUiThread(new Runnable() {

@Override

public 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

@Override

public void onServicesDiscovered(BluetoothGatt gatt, int status) {

super.onServicesDiscovered(gatt, status);

//寻找到服务时

if (status == bluetoothGatt.GATT_SUCCESS) {

//得到连接设备的所有服务

final List services = bluetoothGatt.getServices();

runOnUiThread(new Runnable() {

@Override

public void run() {

//遍历所有服务

for (final BluetoothGattService bluetoothGattService : services) {

bluetoothGattServices = bluetoothGattService;

Log.i(TAG, "onServicesDiscovered: " + bluetoothGattService.getUuid());//输出服务对应的uuid

//将当前遍历的服务的characteristic放入list中

List charc = bluetoothGattService.getCharacteristics();

//遍历当前服务下的所有characteristic

for (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());

}

}

});

}

}

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

最后

**一个零基础的新人,我认为坚持是最最重要的。**我的很多朋友都找我来学习过,我也很用心的教他们,可是不到一个月就坚持不下来了。我认为他们坚持不下来有两点主要原因:

他们打算入行不是因为兴趣,而是因为所谓的IT行业工资高,或者说完全对未来没有任何规划。

刚开始学的时候确实很枯燥,这确实对你是个考验,所以说坚持下来也很不容易,但是如果你有兴趣就不会认为这是累,不会认为这很枯燥,总之还是贵在坚持。

技术提升遇到瓶颈了?缺高级Android进阶视频学习提升自己吗?还有大量大厂面试题为你面试做准备!

提升自己去挑战一下BAT面试难关吧

对于很多Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。整理的这些知识图谱希望对Android开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。

不论遇到什么困难,都不应该成为我们放弃的理由!

如果有什么疑问的可以直接私我,我尽自己最大力量帮助你!

最后祝各位新人都能坚持下来,学有所成。

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!

这些内容对你有帮助,可以扫码获取!!(备注:Android)**

最后

**一个零基础的新人,我认为坚持是最最重要的。**我的很多朋友都找我来学习过,我也很用心的教他们,可是不到一个月就坚持不下来了。我认为他们坚持不下来有两点主要原因:

他们打算入行不是因为兴趣,而是因为所谓的IT行业工资高,或者说完全对未来没有任何规划。

刚开始学的时候确实很枯燥,这确实对你是个考验,所以说坚持下来也很不容易,但是如果你有兴趣就不会认为这是累,不会认为这很枯燥,总之还是贵在坚持。

技术提升遇到瓶颈了?缺高级Android进阶视频学习提升自己吗?还有大量大厂面试题为你面试做准备!

提升自己去挑战一下BAT面试难关吧

[外链图片转存中…(img-3IMakCe8-1712401148795)]

对于很多Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。整理的这些知识图谱希望对Android开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。

不论遇到什么困难,都不应该成为我们放弃的理由!

如果有什么疑问的可以直接私我,我尽自己最大力量帮助你!

最后祝各位新人都能坚持下来,学有所成。

《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》,点击传送门即可获取!
  • 23
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值