实现Android设备蓝牙之间的自动配对

news/2024/7/7 6:41:13 标签: android, elasticsearch, 大数据

     在很多业务场景中,某些蓝牙是需要自动配对的,为了给用户提供便利,而不是要用户去手动配对,这么做主要是为了提高用户体验。废话不多说上代码:

一、BlutoothPariUtils


public class BlutoothPariUtils {

    static public boolean autoBond(Class btClass, BluetoothDevice device, String strPin) throws Exception {
        Method autoBondMethod = btClass.getMethod("setPin", new Class[] { byte[].class });
        Boolean result = (Boolean) autoBondMethod.invoke(device, new Object[] { strPin.getBytes() });
        return result;
    }

    /**
     * 与设备配对 参考源码: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 block
            e.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 block
            e.printStackTrace();
        }
    }

}

二、BluetoothReceiver


public class BluetoothReceiver extends BroadcastReceiver {


    private static final String TAG = "BluetoothReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {

        // 从Intent中获取设备对象
        BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //获取 action
        String action = intent.getAction();
        if ("android.bluetooth.device.action.PAIRING_REQUEST".equals(action)) {
            Log.i(TAG, "##### 是配对请求的请求 ######");

            //判断是否是  北斗设备

            Log.i(TAG, "####### 北斗设备  #######");
            Bundle extras = intent.getExtras();
            Log.i(TAG, "-->" + extras.toString());
            Object device = extras.get("android.bluetooth.device.extra.DEVICE");
            Object pairkey = extras.get("android.bluetooth.device.extra.PAIRING_KEY");
            Log.i(TAG, "device-->" + String.valueOf(device));
            Log.i(TAG, "pairkey-->" + String.valueOf(pairkey));

            try {
                BlutoothPariUtils.setPairingConfirmation(btDevice.getClass(), btDevice, true);
                Log.i("order...", "isOrderedBroadcast:" + isOrderedBroadcast() + ",isInitialStickyBroadcast:" + isInitialStickyBroadcast());
                abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。
                //3.调用setPin方法进行配对...
                boolean ret = BlutoothPariUtils.setPin(btDevice.getClass(), btDevice, String.valueOf(pairkey));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
    }


}

三、静态注册广播

  <!-- 蓝牙增加一个配对码广播监听 -->
        <receiver
            android:name="csu.xiaoya.robotApp.blutooth_libs.blt_receiver.BluetoothReceiver"
            android:exported="true">
            <intent-filter>
                <!-- 捕捉配对请求 -->
                <action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
            </intent-filter>

        </receiver>

四、完成

    代码引用BlutoothPariUtils.createBond(,);

   


http://www.niftyadmin.cn/n/5319716.html

相关文章

SQL-分组查询

&#x1f389;欢迎您来到我的MySQL基础复习专栏 ☆* o(≧▽≦)o *☆哈喽~我是小小恶斯法克&#x1f379; ✨博客主页&#xff1a;小小恶斯法克的博客 &#x1f388;该系列文章专栏&#xff1a;重拾MySQL &#x1f379;文章作者技术和水平很有限&#xff0c;如果文中出现错误&am…

Python学习从0到1 day2 python注释

那就祝我们 all is well ——24.1.12 一、python中的注释 1.注释的作用 注释代码与非注释代码对比&#xff0c;可以发现&#xff0c;添加了注释的代码更加易于程序的阅读 2.注释的分类及方法 注释在python中有两种形式&#xff1a;单行注释和多行注释。 单行注释只能注释一行…

创建一个英雄表(hero)

1、创建一个英雄表(hero) 主键 name nickname address groups email telphone 2、博客&#xff1a;window系统安装MySQL 1、创建一个英雄表(hero) 1.1 创建一个数据库test 1.2创建一个表hero 1.3插入内容 window系统…

uni-app修改头像和个人信息

效果图 代码&#xff08;总&#xff09; <script setup lang"ts"> import { reqMember, reqMemberProfile } from /services/member/member import type { MemberResult, Gender } from /services/member/type import { onLoad } from dcloudio/uni-app impor…

计算机找不到msvcr100.dll的多种解决方法分享,轻松解决dll问题

msvcr100.dll作为系统运行过程中不可或缺的一部分&#xff0c;它的主要功能在于提供必要的运行时支持&#xff0c;确保相关应用程序能够顺利完成编译和执行。因此&#xff0c;当操作系统或应用程序在运行阶段搜索不到该文件时&#xff0c;自然会导致各类依赖于它的代码无法正常…

PostMan、LoadRunner进行并发压测流程

需求 两个记账接口在同一时间大量处理同一账户账务时&#xff0c;锁表顺序不同导致死锁&#xff0c;在修改完代码后模拟生产记账流程进行测试&#xff0c;需要对两个接口进行并发测试。 在进行压测的时候&#xff0c;需要对流水号进行递增。 PostMan处理流程 1. 新建Collection…

Redis(三)持久化

文章目录 RDB&#xff08;Redis Database&#xff09;自动触发保存频率修改dump文件保存路径修改文件保存名称dump恢复 手动触发save![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/a56fdff44aee4efa96c2ce3615b69dc1.png)bgsave 优劣优点缺点 检查修复dump文件会触…

DEJA_VU3D - Cesium功能集 之 113-获取圆节点(2)

前言 编写这个专栏主要目的是对工作之中基于Cesium实现过的功能进行整合,有自己琢磨实现的,也有参考其他大神后整理实现的,初步算了算现在有差不多实现小140个左右的功能,后续也会不断的追加,所以暂时打算一周2-3更的样子来更新本专栏(每篇博文都会奉上完整demo的源代码…