android 实现ble蓝牙自动配对连接

article/2025/10/8 10:21:28

蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框。

本文章用来连接蓝牙设备ai-thinker,如果你要连接其他蓝牙设备,注意修改相关名字以及修改设备初试pin值。

将Demo安装在Android手机上,点击按钮,可以实现与目标蓝牙设备的自动配对。

以下是涉及的代码,两个类一个activity:

 实现是activity_main:

<?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"tools:context=".MainActivity"><Buttonandroid:id="@+id/btn_autopair"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Hello World!"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" /></androidx.constraintlayout.widget.ConstraintLayout>
ClsUtils:
package com.example.myapplication;
import java.lang.reflect.Field;
import java.lang.reflect.Method;import android.bluetooth.BluetoothDevice;
import android.util.Log;
public class ClsUtils{/*** 与设备配对 参考源码:platform/packages/apps/Settings.git* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java*/static public boolean createBond(Class btClass, BluetoothDevice btDevice)throws Exception{Method createBondMethod = btClass.getMethod("createBond");Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);return returnValue.booleanValue();}/*** 与设备解除配对 参考源码:platform/packages/apps/Settings.git* /Settings/src/com/android/settings/bluetooth/CachedBluetoothDevice.java*/static public boolean removeBond(Class btClass, BluetoothDevice btDevice)throws Exception{Method removeBondMethod = btClass.getMethod("removeBond");Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);return returnValue.booleanValue();}static public boolean setPin(Class btClass, BluetoothDevice btDevice,String str) throws Exception{try{Method removeBondMethod = btClass.getDeclaredMethod("setPin",new Class[]{byte[].class});Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice,new Object[]{str.getBytes()});Log.e("returnValue", "" + returnValue);}catch (SecurityException e){// throw new RuntimeException(e.getMessage());e.printStackTrace();}catch (IllegalArgumentException e){// throw new RuntimeException(e.getMessage());e.printStackTrace();}catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();}return true;}// 取消用户输入static public boolean cancelPairingUserInput(Class btClass,BluetoothDevice device)throws Exception{Method createBondMethod = btClass.getMethod("cancelPairingUserInput");// cancelBondProcess()Boolean returnValue = (Boolean) createBondMethod.invoke(device);return returnValue.booleanValue();}// 取消配对static public boolean cancelBondProcess(Class btClass,BluetoothDevice device)throws Exception{Method createBondMethod = btClass.getMethod("cancelBondProcess");Boolean returnValue = (Boolean) createBondMethod.invoke(device);return returnValue.booleanValue();}/**** @param clsShow*/static public void printAllInform(Class clsShow){try{// 取得所有方法Method[] hideMethod = clsShow.getMethods();int i = 0;for (; i < hideMethod.length; i++){Log.e("method name", hideMethod[i].getName() + ";and the i is:"+ i);}// 取得所有常量Field[] allFields = clsShow.getFields();for (i = 0; i < allFields.length; i++){Log.e("Field name", allFields[i].getName());}}catch (SecurityException e){// throw new RuntimeException(e.getMessage());e.printStackTrace();}catch (IllegalArgumentException e){// throw new RuntimeException(e.getMessage());e.printStackTrace();}catch (Exception e){// TODO Auto-generated catch blocke.printStackTrace();}}//确认配对static public void setPairingConfirmation(Class<?> btClass,BluetoothDevice device,boolean isConfirm)throws Exception{Method setPairingConfirmation = btClass.getDeclaredMethod("setPairingConfirmation",boolean.class);setPairingConfirmation.invoke(device,isConfirm);}
}
MainActivity:
package com.example.myapplication;import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;public class MainActivity extends Activity implements OnClickListener{/** Called when the activity is first created. */private static BluetoothDevice remoteDevice=null;private Button btn_autopair=null;final static String ACTION_BLUETOOTHBC="android.bluetooth.device.action.PAIRING_REQUEST";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn_autopair=(Button)findViewById(R.id.btn_autopair);btn_autopair.setOnClickListener(this);}public static boolean pair(String strAddr, String strPsw){boolean result = false;//蓝牙设备适配器BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//取消发现当前设备的过程bluetoothAdapter.cancelDiscovery();if (!bluetoothAdapter.isEnabled()){bluetoothAdapter.enable();}if (!BluetoothAdapter.checkBluetoothAddress(strAddr)){ // 检查蓝牙地址是否有效Log.d("mylog", "devAdd un effient!");}//由蓝牙设备地址获得另一蓝牙设备对象BluetoothDevice device = bluetoothAdapter.getRemoteDevice(strAddr);if (device.getBondState() != BluetoothDevice.BOND_BONDED){try{Log.d("mylog", "NOT BOND_BONDED");ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对ClsUtils.createBond(device.getClass(), device);//    ClsUtils.cancelPairingUserInput(device.getClass(), device);remoteDevice = device; // 配对完毕就把这个设备对象传给全局的remoteDeviceresult = true;}catch (Exception e){// TODO Auto-generated catch blockLog.d("mylog", "setPiN failed!");e.printStackTrace();} //}else{Log.d("mylog", "HAS BOND_BONDED");try{//ClsUtils这个类的的以下静态方法都是通过反射机制得到需要的方法ClsUtils.createBond(device.getClass(), device);//创建绑定ClsUtils.setPin(device.getClass(), device, strPsw); // 手机和蓝牙采集器配对ClsUtils.createBond(device.getClass(), device);//    ClsUtils.cancelPairingUserInput(device.getClass(), device);remoteDevice = device; // 如果绑定成功,就直接把这个设备对象传给全局的remoteDeviceresult = true;}catch (Exception e){// TODO Auto-generated catch blockLog.d("mylog", "setPiN failed!");e.printStackTrace();}}return result;}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch (v.getId()) {case R.id.btn_autopair:if (pair("94:C9:60:1E:00:04", "123456")) {//pair的第一个参数是要配对的蓝牙地址,第二个参数是配对时预先设置的密钥Log.i("aaron", remoteDevice.getAddress());}break;default:break;}}
}

最后别忘了加上权限哦 AndroidManifest.xml:

(权限太多了 忘记是哪个了。)

   <!-- 使用蓝牙的权限 --><uses-permission android:name="android.permission.BLUETOOTH" /> <!-- 扫描蓝牙设备或者操作蓝牙设置 --><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <!-- 模糊定位权限,仅作用于6.0+ --><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 精准定位权限,仅作用于6.0+ --><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /><uses-permission android:name="android.permission.BLUETOOTH_SCAN" /><uses-sdkandroid:minSdkVersion="8"android:targetSdkVersion="21" /><uses-permission android:name="android.permission.BLUETOOTH"/><uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

最后我发现这样子运行还是有pin码的弹窗 如以下:

 这时候就让硬件工程师帮你把pin码给取消掉就好了,取消之后就没有这个对话框了。

不过我发现一个问题,这个代码在小米手机运行没问题。在华为手机上会不稳定,有时候会报错。本文章只是记录学习过程中的一些小问题,如有错误请指正。


http://chatgpt.dhexx.cn/article/msFbhucO.shtml

相关文章

一篇文章带你解读蓝牙配对绑定

BLE配对绑定解读 什么是低功耗蓝牙配对&#xff1f;什么又是绑定&#xff1f;配对和绑定有什么区别&#xff1f;配对有什么好处&#xff1f;如何删除绑定信息&#xff1f;如何确定配对的安全等级&#xff1f;just work的配对一定就不安全吗&#xff1f;如何开发自己的配对应用…

蓝牙配对流程(一)

一、扫描 被动扫描&#xff08;主从之间没有扫描请求与扫描响应&#xff09; 2.主动扫描&#xff08;主从之间有扫描请求与扫描响应&#xff09; 二、过滤 1、信息匹配&#xff08;是否在白名单&#xff09; 三、建立连接 1、建立连接 建立连接后的结果&#xff1a; 连接成…

蓝牙协议和配对

蓝牙协议 蓝牙协议分层 物理层&#xff08;PHA&#xff09;&#xff0c;链路层&#xff08;LL&#xff09;&#xff0c;HCI&#xff08;可选&#xff09;,GAP层&#xff0c;L2CAP&#xff0c;SMP &#xff0c; ATT &#xff0c;GATT GAP层角色总结 对于蓝牙的主机和蓝牙的从…

蓝牙(二)蓝牙搜索、配对、连接

1.搜索 从上一节我们可以知道&#xff0c;蓝牙状态发生了改变&#xff0c;并发生了回调。咱们就从回调开始。 DevicePickerFragment.java 用于蓝牙设置界面的蓝牙配置和管理 Overridepublic void onBluetoothStateChanged(int bluetoothState) {super.onBluetoothStateChange…

Android蓝牙配对

上一篇博客介绍了Android ble的一些情况。 http://blog.csdn.net/guijiaoba/article/details/41172403 蓝牙如果链接好&#xff0c;能够读写&#xff0c;基本上完成了。蓝牙还有个比较烦人的东西&#xff0c;就是蓝牙配对。 Android ble4.0使用的配对方式和原先版本的配对方式…

Android蓝牙开发(二)之蓝牙配对和蓝牙连接

上篇文章&#xff1a;https://blog.csdn.net/huangliniqng/article/details/82185983 讲解了打开蓝牙设备和搜索蓝牙设备&#xff0c;这篇文章来讲解蓝牙配对和蓝牙连接 1.蓝牙配对 搜索到蓝牙设备后&#xff0c;将设备信息填充到listview中&#xff0c;点击listiew则请求配对…

BLE蓝牙的连接和配对过程

一 连接 同一款手机&#xff0c;为什么跟某些设备可以连接成功&#xff0c;而跟另外一些设备又连接不成功&#xff1f;同一个设备&#xff0c;为什么跟某些手机可以建立连接&#xff0c;而跟另外一些手机又无法建立连接&#xff1f;同一个手机&#xff0c;同一个设备&#xff…

BLE蓝牙的配对过程浅析

BLE蓝牙配对过程 在了解到Bluetooth协议的大概后&#xff0c;本篇文章简单的梳理一下BLE蓝牙的配对过程和配对过程的数据格式&#xff0c;对于后面理解蓝牙的集中配对模式及相关漏洞浅浅奠定一下基础。 和经典蓝牙一样&#xff0c;协议为处于连接状态的BLE设备&#xff0c;定…

蓝牙设备的连接与配对

蓝牙是一种短距离无线通信技术&#xff0c;它由爱立信公司于1994年创制&#xff0c;原本想替代连接电信设备的数据线&#xff0c;但是后来发现它也能用于移动设备之间的数据传输&#xff0c;所以蓝牙技术在手机上获得了长足发展。 因为手机内部的通讯芯片一般同时集成了2G/3G/4…

Android 蓝牙连接,蓝牙配对,自动连接蓝牙

趁热打铁&#xff0c;这篇文章写于刚写完蓝牙配对Demo&#xff0c;主要介绍配对蓝牙的具体编码步骤&#xff0c;开整! 首先上效果图&#xff0c;看一下是否符合读者现在的需求 主要核心代码没有想象中那么复杂&#xff0c;首先要去申请一下权限&#xff0c;不仅需要蓝牙权限…

蓝牙配对方式

4种蓝牙配对方式&#xff0c;通俗地说&#xff1a; 1.Numeric Comparison&#xff1a;配对双方都显示一个6位的数字&#xff0c;由用户来核对数字是否一致&#xff0c;一致即可配对。例如手机之间的配对。 2.Just Works&#xff1a;用于配对没有显示没有输入的设备&#xff0c;…

蓝牙的配对和连接的建立过程

蓝牙的建立过程是一个复杂的过程&#xff0c;即使有过相当一段工作和使用经验的人&#xff0c;如果不仔细去了解还是理解不全。 平时我们用蓝牙耳机听音乐&#xff0c;和不同的设备共享文件&#xff0c;打电话等&#xff0c;都有一个配对--连接--传输数据的过程。 配对&#…

蓝牙|标准蓝牙配对方式

蓝牙:BlueTooth,是一种无线技术标准&#xff0c;可实现固定设备、移动设备和楼宇个人域网之间的短距离数据交换&#xff0c;蓝牙又分为传统/标准蓝牙和BLE蓝牙。 在了解配对方式前&#xff0c;先了解设备的IOCapacity,IOCapcaity是由设备InputCapacity和OutputCapacity组合而成…

蓝牙学习八(配对与绑定)

1.简介 Paring&#xff08;配对&#xff09;和Bonding&#xff08;绑定&#xff09;是实现蓝牙射频通信安全的一种机制&#xff0c;有两点需要注意&#xff1a; Paring/bonding实现的是蓝牙链路层的安全&#xff0c;对应用层来说是完全透明的。也就是说&#xff0c;不管有没有…

蓝牙 - 配对和连接

什么是蓝牙配对&#xff1f; 蓝牙配对是为了连接设备的一种信息注册方法。通过在设备之间注册设备信息&#xff08;配对&#xff09;&#xff0c;它们可以连接。要使用一个蓝牙设备&#xff0c;你必须首先将其与另一个蓝牙设备配对。配对有点像交换电话号码。类似于你必须与你…

Java 接口回调机制

日常开发中接口回调机制无处不在&#xff0c;刚开始用时却总是晕晕乎乎&#xff0c;网上也有很多相关的文章介绍&#xff0c;但总是没有看得太明白&#xff0c;今天端午假期正好花时间来总结一下&#xff0c;我们按如下顺序介绍 一、什么是接口回调 在应用开发中&#xff0c;接…

Android 接口回调

Android接口回调讲解 回调定义回调机制回调意义接口回调的实现步骤参考 网上看了一堆&#xff0c;感觉有点零散&#xff0c;我自己总结一下。 回调定义 正式定义 回调函数就是一个通过函数指针调用的函数。如果你把函数的指针&#xff08;地址&#xff09;作为参数传递给另一…

理解Java接口回调

初步认识&#xff1a; 实现步骤&#xff1a; 1、创建一个回调接口。 2、创建一个回调对象实现回调接口。 3、创建一个控制器对象&#xff0c;将回调对象作为参数传给控制器对象&#xff0c;控制器对象负责检查某个场景是否出现或某个条件是否满足&#xff0c;当满足时&#…

Android 自定义接口回调

1.定义一个简单的接口回调 下面是定义一个简单的接口&#xff0c;实现的功能是&#xff0c;设置名字爱好&#xff0c;并且返回给主 Activity。 1.1 自定义一个接口 定义一个名字为 setNameListener() 的接口类&#xff1a; /*** author: wu* date: on 2018/10/23.* describ…

接口回调(笔记

接口回调讲解 回调定义回调机制回调意义接口回调的实现步骤参考 网上看了一堆&#xff0c;感觉有点零散&#xff0c;我自己总结一下。看评论区说存在很多问题&#xff0c;我读了一下&#xff0c;雀氏存在一些&#xff0c;非常感谢批评指正&#xff0c;我重新写一写。&#xff0…