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

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

一、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(,);

相关推荐
L72566 分钟前
Android的Handler
android
清风徐来辽7 分钟前
Android HandlerThread 基础
android
HerayChen1 小时前
HbuildderX运行到手机或模拟器的Android App基座识别不到设备 mac
android·macos·智能手机
顾北川_野1 小时前
Android 手机设备的OEM-unlock解锁 和 adb push文件
android·java
hairenjing11231 小时前
在 Android 手机上从SD 卡恢复数据的 6 个有效应用程序
android·人工智能·windows·macos·智能手机
小黄人软件2 小时前
android浏览器源码 可输入地址或关键词搜索 android studio 2024 可开发可改地址
android·ide·android studio
拓端研究室TRL2 小时前
【梯度提升专题】XGBoost、Adaboost、CatBoost预测合集:抗乳腺癌药物优化、信贷风控、比特币应用|附数据代码...
大数据
黄焖鸡能干四碗2 小时前
信息化运维方案,实施方案,开发方案,信息中心安全运维资料(软件资料word)
大数据·人工智能·软件需求·设计规范·规格说明书
dj15402252032 小时前
group_concat配置影响程序出bug
android·bug
编码小袁2 小时前
探索数据科学与大数据技术专业本科生的广阔就业前景
大数据