2024年最新安卓基于BLE的蓝牙开发入门,互联网大厂面试难度排行

【附】相关架构及资料

源码、笔记、视频。高级UI、性能优化、架构师课程、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter全方面的Android进阶实践技术,和技术大牛一起讨论交流解决问题。

image

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

此时我们已经通过上述三个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/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;

推荐学习资料

  • Android进阶学习全套手册

  • Android对标阿里P7学习视频

  • BAT TMD大厂Android高频面试题

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

//获取连接设备的服务

bluetoothGatt.discoverServices();

break;

case BluetoothGatt.STATE_CONNECTING:

connection_Status.setText(“正在连接”);

break;

case BluetoothGatt.STATE_DISCONNECTED:

connection_Status.setText(“已断开”);

break;

推荐学习资料

  • Android进阶学习全套手册

    [外链图片转存中…(img-SrmTLE2T-1715146611621)]

  • Android对标阿里P7学习视频

    [外链图片转存中…(img-YBYbAos7-1715146611621)]

  • BAT TMD大厂Android高频面试题

[外链图片转存中…(img-kNSCabhD-1715146611622)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值