实现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(,);

   

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android操作系统具有本身具有蓝牙功能,并且提供蓝牙API,方便开发人员进行蓝牙开发。本文将介绍如何创建一个蓝牙搜索、自动配对和通信的Demo。 首先,在应用程序清单文件中请求蓝牙权限。在应用程序清单文件中,应该添加以下代码: ``` <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> ``` 然后,在MainActivity中,创建一个BluetoothAdapter的实例并启用蓝牙。接下来,创建一个广播接收器来响应搜索、配对和连接的事件。使用设备的名称和地址作为数据存储在搜索结果中。然后,在UI上显示搜索到的设备列表。在使用设备进行通信之前,需要与其进行配对。使用createBond()方法自动配对设备。 ``` bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!bluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String name = device.getName(); String address = device.getAddress(); // add device to list deviceList.add(name + "\n" + address); listAdapter.notifyDataSetChanged(); } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() == BluetoothDevice.BOND_BONDED) { // connect to device for communication connectToDevice(device); } } } }; searchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { deviceList.clear(); bluetoothAdapter.startDiscovery(); registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)); } }); private void connectToDevice(BluetoothDevice device) { BluetoothSocket socket = null; try { socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect(); // start communication } catch (IOException e) { e.printStackTrace(); } } ``` 在这个Demo中,当用户点击搜索按钮时,应用程序将开始搜索周围的设备。当找到设备时,列表将显示设备的名称和地址。然后,当用户选择列表中的设备时,设备将尝试自动配对。如果配对成功,应用程序将使用BluetoothSocket进行通信。 总之,这是一个简单但完整的Android蓝牙搜索、自动配对和通信的Demo,用于学习蓝牙开发的基本思想和方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值