最近在开发一个手机连接蓝牙设备的APP,其中有个需求是自动连接,用户不用确认。我在网上找到了一个工具类,但是网上很

多文章对这个工具类的使用方法都不能实现我的需求,要么弹出框不能隐藏,要么是隐藏输入框却不能配对成功。经过我多次尝

试,发现他们的配对方法用错了。

工具类:ClsUtils.java


/**************** 蓝牙配对函数 ***************/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<? extends BluetoothDevice> 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) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}return true;}// 取消用户输入static public boolean cancelPairingUserInput(Class<?> btClass, BluetoothDevice device) throws Exception {Method createBondMethod = btClass.getMethod("cancelPairingUserInput");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();}//确认配对static public void setPairingConfirmation(Class<?> btClass, BluetoothDevice device, boolean isConfirm) throws Exception {Method setPairingConfirmation = btClass.getDeclaredMethod("setPairingConfirmation", boolean.class);setPairingConfirmation.invoke(device, isConfirm);}/**** @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) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}
}

实现的界面,没有采用在Manifest文件里配置receiver的方法,因为发现那样配置结果还是会闪出配对密码输入框,附配对代码

本方法是根据蓝牙名称进行配对的,如需求不同可以自己该代码,不适用配对手机蓝牙设备,只适用于硬件开发中蓝牙模块中需

要输入密码的配对,(layout文件里只有一个按钮,这里就不给代码了):


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;public class MainActivity extends AppCompatActivity {private BluetoothAdapter bluetoothAdapter;private BluetoothDevice bluetoothDevice;private Button search;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//开始配对按钮search = findViewById(R.id.search_bluetooth);bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//检查蓝牙if(bluetoothAdapter != null){if(!bluetoothAdapter.isEnabled()){Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);//设置蓝牙可见性intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,3000);this.startActivity(intent);//打开蓝牙bluetoothAdapter.enable();}}else {Toast.makeText(this,"本地设备驱动异常",Toast.LENGTH_LONG).show();}search.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//扫描设备bluetoothAdapter.startDiscovery();//注册广播RegisterBluetoothReceiver();}});}//注册广播public void RegisterBluetoothReceiver(){// 设置广播信息过滤IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(BluetoothDevice.ACTION_FOUND);intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);// 注册广播接收器,接收并处理搜索结果registerReceiver(BTReceive, intentFilter);}//处理蓝夜绑定的广播private BroadcastReceiver BTReceive = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();if(BluetoothDevice.ACTION_FOUND.equals(action)){bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);String bluetoothName;if((bluetoothName = bluetoothDevice.getName()) != null){// 如果查找到的设备符合要连接的设备,处理if (bluetoothName.equalsIgnoreCase("HC-05")) {//搜索蓝牙占用资源,搜索到后要及时关闭bluetoothAdapter.cancelDiscovery();//获取蓝牙的连接状态int connectState = bluetoothDevice.getBondState();switch (connectState){//未配对case BluetoothDevice.BOND_NONE://开始配对try{ClsUtils.createBond(bluetoothDevice.getClass(),bluetoothDevice);}catch (Exception e){e.printStackTrace();}break;}}}}else if(BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)){try {//如果不结束广播接收,配对界面会闪出abortBroadcast();//顺序一定要这样,否则会出问题ClsUtils.setPin(bluetoothDevice.getClass(), bluetoothDevice, "1234");//这行代码会在控制台报错//ClsUtils.setPairingConfirmation(bluetoothDevice.getClass(), bluetoothDevice,true);}catch (Exception e){e.printStackTrace();}}}};@Overrideprotected void onDestroy() {super.onDestroy();//注销广播unregisterReceiver(BTReceive);}}

参考文章:https://blog.csdn.net/qq_30297763/article/details/79621137

Android 蓝牙 自动配对连接相关推荐

  1. android蓝牙配对 自动联接,Android系统下蓝牙自动配对连接方法

    Android系统下蓝牙自动配对连接方法 [专利摘要]本发明涉及一种Android系统下蓝牙自动配对连接方法,其包括如下步骤:步骤1.在Android设备端内存储上次进行蓝牙连接蓝牙外设的蓝牙地址,并 ...

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

    蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 本文章用来连接蓝牙设备ai-thinker,如果你要连接其他蓝牙设备,注意修改相关名字以及修改设备初试pin值 ...

  3. 【转载】Android蓝牙自动配对Demo

    注:新版本安卓需增加权限 <uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION ...

  4. android 实现蓝牙自动配对连接,Android实践 -- Android蓝牙设置连接

    蓝牙开发相关 使用Android Bluetooth APIs将设备通过蓝牙连接并通信,设置蓝牙,查找蓝牙设备,配对蓝牙设备 连接并传输数据,以下是Android系统提供的蓝牙相关的类和接口 Blue ...

  5. Android 蓝牙自动匹配PIN码跳过用户交互

    近期项目中需要连接蓝牙设备,起初只是设置蓝牙列表界面让用户点击然后输入默认PIN码,后来改需求了 = = ,要求自动连接指定设备并不需要用户手动输入PIN码,作为Android 小白的我是拒绝的,但是 ...

  6. Android下的蓝牙自动配对

    转载        源码下载地址 经过最近一段时间得研究,针对网上给出的案例.总结了一个亲测好使的Demo. 说明如下: 1.本Demo用来连接蓝牙设备HC-05,如果你要连接其他蓝牙设备,注意修改相 ...

  7. 蓝牙自动配对警惕PIN码漏洞攻击

    蓝牙自动配对警惕PIN码漏洞攻击 配对是蓝牙设备间身份认证的一个过程,只有成功配对的两个设备才能连接并进行数据交互,所以配对是蓝牙操作中必不可少的流程. 在<蓝牙配对协议分析一>和< ...

  8. android蓝牙配对 自动联接,如何实现android蓝牙开发 自动配对连接,并不弹出提示框...

    之前做一个android版的蓝牙 与血压计通讯的项目,遇到最大的难题就是自动配对. 上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了 我就 ...

  9. android 提示蓝牙无法配对,如何实现android蓝牙开发 自动配对连接,并不弹出提示框...

    之前做一个android版的蓝牙 与血压计通讯的项目,遇到最大的难题就是自动配对. 上网查资料说是用反射createBond()和setPin(),但测试时进行配对还是会出现提示,但配对是成功了 我就 ...

  10. android 蓝牙自动连接,蓝牙自动连接实现

    实现的主要功能(蓝牙配对成功如何与远程设备一直连接) 1.当蓝牙配对成功连接时,断开远程端设备会自动连接 2.当设备长时间锁屏会导致CachedBluetoothDevice自动清空,如果蓝牙断开就不 ...

最新文章

  1. 世界无烟日丨如何科学戒烟?
  2. Coursera课程Python for everyone:chapter10
  3. 关于jHipster框架在构建中的出现的error修复
  4. C#实现 Linq 序列的Distinct—— IEnumerable.Distinct()——IEqualityComparer
  5. webpack的简介---webpack工作笔记001
  6. git 怎么备份本地分支_同步管理本地git仓库和github仓库上的分支
  7. wepack中loader的分类
  8. bootstrap课程5 bootstrap中的组件使用的注意事项是什么
  9. 擦拭法 java 泛型_廖雪峰Java4反射与泛型-3范型-4擦拭法
  10. 一些网络爱好者常用的网络工具
  11. 小米路由器 charles无法抓包
  12. 数据分析挖掘全套课程视频spss/sas/R/excel/案例实战体系教学
  13. mi5splus android9,小米5s plus和华为mate9买哪个好 小米5sPlus和华为mate9区别对比评测...
  14. 银行数据仓库体系实践(14)--数据应用之内部报表及数据分析
  15. html网页挂马,浏览器安全之网页挂马实战 ——合天网安实验室学习笔记
  16. 剪贴板是计算机系统,剪贴板怎么打开,小编教你电脑剪贴板怎么打开
  17. 静态资源文件无法加载导致jsp页面渲染不成功问题
  18. 使用 Typora 画图
  19. 对图片进行剪切,保留原始比例
  20. scrapy多个url爬虫

热门文章

  1. depends.exe 使用说明
  2. 旧手机上的微信数据丢失怎么才能恢复回来
  3. 专门查英语单词的软件_查英语单词的软件
  4. 1.1音响系统放大器设计
  5. handler机制详解
  6. CrossApp V1.0.1,新增动画与连接 wifi 功能
  7. 非线性光学近似计算机应用,浅谈非线性光学的发展及应用
  8. JavaMail的使用
  9. 协同过滤算法及python实现
  10. 《虚幻4 VR开发指南》视频教程