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

首先说一下之后会用到的关于蓝牙方面的东西:

  • 断开蓝牙已配对的设备
  • 搜索附近蓝牙设备
  • 拦截用户交互页面,使用代码输入
  • 由于在最后连接的时候使用的是设备的SDK所以在这里就不介绍了

1.断开已配对设备

最后在项目中发现没有用。这里就先记录一下。

    //得到配对的设备列表,清除已配对的设备public void removePairDevice() {if (mBluetoothAdapter != null) {//mBluetoothAdapter初始化方式 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//这个就是获取已配对蓝牙列表的方法Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();for (BluetoothDevice device : bondedDevices) {//这里可以通过device.getName()  device.getAddress()来判断是否是自己需要断开的设备unpairDevice(device);}}}//反射来调用BluetoothDevice.removeBond取消设备的配对private void unpairDevice(BluetoothDevice device) {try {Method m = device.getClass().getMethod("removeBond", (Class[]) null);m.invoke(device, (Object[]) null);} catch (Exception e) {Log.e("mate", e.getMessage());}}

2.搜索附近蓝牙

首先我们需要注册两个广播,第一个为正在搜索时的,第二个为搜索完成的。

        // Register for broadcasts when a device is discoveredIntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);this.registerReceiver(mFindBlueToothReceiver, filter);// Register for broadcasts when discovery has finishedfilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);this.registerReceiver(mFindBlueToothReceiver, filter);//需要时开始搜索if (mBluetoothAdapter.isDiscovering()) {mBluetoothAdapter.cancelDiscovery();}mBluetoothAdapter.startDiscovery();

然后对广播进行处理。这里要说明一下ClsUtils.createBond()这个方法如果连接设备SDK中有配对的方法,建议把这个方法去掉,我这里是去掉的,加上的话偶尔会Toast出无法配对。

 private final BroadcastReceiver mFindBlueToothReceiver = new BroadcastReceiver() {@Overridepublic void onReceive(Context context, Intent intent) {String action = intent.getAction();// When discovery finds a deviceif (BluetoothDevice.ACTION_FOUND.equals(action)) {//TODO 开始搜索BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);//   if (device.getBondState() != BluetoothDevice.BOND_BONDED) {//判断蓝牙状态,是否是已配对//TODO 可以在这判断名字 如果搜索结束后没有,再到已配对中寻找String BTName[] = device.getName().split("-");if (BTName[0].equals("xxx")) {//在这连接设备 一般需要蓝牙地址 device.getAddress();try {ClsUtils.createBond(device.getClass(), device);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}//  }} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {//TODO 搜索结束Toast.makeText(context, "搜索结束",Toast.LENGTH_SHORT).show();}}};

这里在Activity结束时记得取消注册和取消搜索

unregisterReceiver(mFindBlueToothReceiver);if (mBluetoothAdapter != null) {mBluetoothAdapter.cancelDiscovery();}

3.拦截用户交互页面

通过广播可以监听到输入PIN码的那个页面将要弹出

       <receiver android:name=".BluetoothConnectActivityReceiver" ><intent-filter android:priority="1000"><action android:name="android.bluetooth.device.action.PAIRING_REQUEST" /></intent-filter></receiver>

广播中需要做的事情,注意一定要调用abortBroadcast(),不然交互页面还是会出现一下然后消失。就是这个方法找了一天(╯‵□′)╯︵┴─┴。。。

public class BluetoothConnectActivityReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {BluetoothDevice mBluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);try {//(三星)4.3版本测试手机还是会弹出用户交互页面(闪一下),如果不注释掉下面这句页面不会取消但可以配对成功。(中兴,魅族4(Flyme 6))5.1版本手机两中情况下都正常//ClsUtils.setPairingConfirmation(mBluetoothDevice.getClass(), mBluetoothDevice, true);abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。//3.调用setPin方法进行配对...boolean ret = ClsUtils.setPin(mBluetoothDevice.getClass(), mBluetoothDevice, "你需要设置的PIN码");} catch (Exception e) {e.printStackTrace();}}}
}

然后只要在搜索到自己需要的设备后连接进行操作就可以了!!!一定要记得加权限~

 <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /><uses-permission android:name="android.permission.BLUETOOTH" />

在Android6.0之后还需要一个模糊定位的权限

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

最后把ClsUtils类奉上,网上有很多的。

/**************** 蓝牙配对函数 ***************/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) {// 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(btClass, device);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) {// 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();}}
}

文章最后提供两篇促使我写这篇文章的背后资源╮( ̄▽ ̄)╭。
Markdown新手指南
Android蓝牙自动配对Demo,亲测好使!!!

第一次写文章,不知道会是什么效果,我的第一次就这么出去了o(〃'▽'〃)o。

Android 蓝牙自动匹配PIN码跳过用户交互相关推荐

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

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

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

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

  3. android 蓝牙自动断开,Android蓝牙:连接()/断开()

    我目前正在设计一个应用程序,它需要连接到设备,写入/读取数据,并可靠地关闭连接.目前我有写/读固体.我的断开连接然后重新连接非常不可靠,并且经常实际上使手机崩溃.我一直在寻找通过大量文章试图弄清楚和. ...

  4. android蓝牙串口arduino源码,android – Arduino:使用串口和软件串口与蓝牙模块

    我的目的是使用Arduino使用HC-05蓝牙模块在PC和 Android设备之间建立通信. 我使用PC和Arduino(串行监视器)之间的USB通信和SoftwareSerial连接到HC-05. ...

  5. android 蓝牙ble调试助手,Android蓝牙调试助手源码分享

    package com.example.android.BluetoothChat; /** * 描述:蓝牙服务核心类 */ import java.io.IOException; import ja ...

  6. Android 蓝牙自动打开并扫描设备,以及获取对方蓝牙设备的种类

    坑是这个样子的:大家可以写一段蓝牙的代码,监测蓝牙设备是否是开启的,如果没有开启请开启蓝牙设备并且扫描周围设备.那么代码就是这个样子的: if (!mAdapter.isEnabled()){mAda ...

  7. Android蓝牙打印二维码打印外卖单打印

    公司在做一个类似美团,饿了么的平台, 所以就会涉及小票打印, 自己懒也难得自己重头开始研究, 就去网上各种找demo,教程之类的. 但是大都是半成品, 只能简单打印一下文字,要么就是没有完整的demo ...

  8. 针对蓝牙PIN码的最新***技术细节分析

    最近,国内外多家网站纷纷刊登了一则关于针对蓝牙PIN码的最新***技术的新闻:通过强制两个正在通讯的蓝牙设备进行重新配对,并监听配对信息,***者可以在0.063秒内破解一个4位(十进制)的PIN码. ...

  9. 车载蓝牙PIN码是什么

    目前大多数汽车都安装了车载蓝牙,但是在初期连接使者需要车主提供 PIN 码,那么车载蓝牙 PIN 码是什么?如果车载蓝牙 PIN 码忘记了怎么办呢?PIN 码分类?手机蓝牙和车载蓝牙连接的方法是什么? ...

最新文章

  1. SAP WM高阶之下架策略M(Small Large Quantity)
  2. CF993E:Nikita and Order Statistics(FFT)
  3. 2 Docker安装及使用
  4. java实验报告合肥工业大学_合肥工业大学 计算机专业 计算方法实验报告
  5. TensorFlow Serving + Docker + Tornado机器学习模型生产级快速部署
  6. php 定时缓存,php如何定时删除缓存??
  7. linux中/bin和/sbin和/usr/bin和/usr/sbin
  8. 一次真实的蓝屏分析 ntkrnlmp.exe
  9. php论坛有哪些_2020面向PHP的5个最佳框架,解释了为什么选择它们
  10. windows nginx 停止和启动_Nginx安装过程详解
  11. php单击图片刷新验证码,thinkphp点击图片刷新验证码
  12. 适配iPhone XR/iPhone XS Max
  13. 2023年天津天狮学院专升本市场营销专业《管理学》考试大纲
  14. 从罗永浩想到东方时尚
  15. 都市青年图鉴:那些喊着奋斗的人,后来怎样了
  16. MySQL的下载与安装详细教程
  17. VS Code 安装和配置 ESLint
  18. 磁盘相关:磁盘IO、扇区、块与页
  19. Odoo产品分析 (三) -- 人力资源板块(5) -- 出勤(1)
  20. python幂指数_幂指数 python

热门文章

  1. 自我求生中的京东科技
  2. android 磁盘检测工具下载,Cross Platform Disk Test app
  3. 外汇天眼:MT4和MT5下架,各个行业大佬是怎么看的?
  4. Linux系统的基本操作
  5. tomcat优化-有改protocol 和 缓存 集群方案 转载自http://passover.blog.51cto.com/2431658/732629
  6. 9.python控制双目摄像头自动拍照
  7. 凡是函数中未指定存储类型_凡是函数中未指定存储类型的局部变量,其隐含的存储类别为    。...
  8. 系统架构设计师-软件水平考试(高级)-理论-计算机网络
  9. 歪理邪说理论之2012年系统架构师软考成绩
  10. 学习微博情感分类的特定情感词嵌入(A14, ACL2014)*