Android 蓝牙自动配对

该博客介绍了一个名为`RegisterBlueTooth`的类,用于实现Android设备与蓝牙设备(如HC-05)的自动配对。首先,开启蓝牙并开始搜索设备,然后注册BroadcastReceiver监听`ACTION_FOUND`和`PAIRING_REQUEST`事件。当找到特定名称的蓝牙设备时,尝试创建配对。如果设备尚未配对,使用工具类`ClsUtils`创建配对,并在配对请求时设置PIN码。最后,连接已配对的设备。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class RegisterBlueTooth {

    Context context;
    public  BluetoothAdapter btAdapt;
    public List<String> lstDevices = new ArrayList<String>();

    public String TagetDeviceAddress;

    private BluetoothReceiver bluetoothReceiver = new BluetoothReceiver();


    public  RegisterBlueTooth(Context context)
    {
        this.context= context;
        openWifiAndBlueTooth();
        btAdapt = BluetoothAdapter.getDefaultAdapter();

        if (!btAdapt.isDiscovering()) {
            btAdapt.startDiscovery();
        }

        register();

    }

    private void register()
    {

        //注册Receiver 来获取蓝牙设备相关的结果
        IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothDevice.ACTION_FOUND);//BroadcastReceiver来获取搜索结果
        intent.addAction("android.bluetooth.device.action.PAIRING_REQUEST");
        context.registerReceiver(bluetoothReceiver, intent);

    }


    private  class BluetoothReceiver extends BroadcastReceiver {

        String pin = "0000";  //此处为你要连接的蓝牙设备的初始密钥,一般为12340000
        public BluetoothReceiver() {

        }

        //广播接收器,当远程蓝牙设备被发现时,回调函数onReceiver()会被执行
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction(); //得到action
            Log.e("action1=", action);
            BluetoothDevice btDevice=null;  //创建一个蓝牙device对象
            // Intent中获取设备对象
            btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            if(BluetoothDevice.ACTION_FOUND.equals(action)){  //发现设备
                Log.e("发现设备:", "[" + btDevice.getName() + "]" + ":" + btDevice.getAddress());

                if(null != btDevice.getName() && btDevice.getName().contains("MPT"))//HC-05设备如果有多个,第一个搜到的那个会被尝试。
                {
                    if (btDevice.getBondState() == BluetoothDevice.BOND_NONE) {// 未配对设备

                        Log.e("zgy", "attemp to bond:" + "[" + btDevice.getName() + "]");
                        try {
                            //通过工具类ClsUtils,调用createBond方法
                            ClsUtils.createBond(btDevice.getClass(), btDevice);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    else if(btDevice.getBondState() == BluetoothDevice.BOND_BONDED) // 以配对设备
                    {
                        TagetDeviceAddress = btDevice.getAddress();
                        WorkService.workThread.connectBt(TagetDeviceAddress);
                    }
                }else
                    {
}
            }else if(action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) //再次得到的action,会等于PAIRING_REQUEST
            {
                Log.e("action2=", action);
                if(null != btDevice.getName() && btDevice.getName().contains("MPT"))
                {
                    Log.e("here", "OKOKOK");

                    try {

                        //1.确认配对
                        ClsUtils.setPairingConfirmation(btDevice.getClass(), btDevice, true);
                        //2.终止有序广播
                        Log.i("order...", "isOrderedBroadcast:" + isOrderedBroadcast() + ",isInitialStickyBroadcast:" + isInitialStickyBroadcast());
                        abortBroadcast();//如果没有将广播终止,则会出现一个一闪而过的配对框。
                        //3.调用setPin方法进行配对...
                        boolean ret = ClsUtils.setPin(btDevice.getClass(), btDevice, pin);
                        TagetDeviceAddress = btDevice.getAddress();
                        WorkService.workThread.connectBt(TagetDeviceAddress);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }else
                    Log.e("提示信息", "这个设备不是目标蓝牙设备");

            }
        }
    }






    private void openWifiAndBlueTooth()
    {
        new Handler().postDelayed(new Runnable() {

            public void run() {
            /* 启动蓝牙 */
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                if (null != adapter) {
                    if (!adapter.isEnabled()) {
                        if (adapter.enable()) {
                            // while(!adapter.isEnabled());
                        } else {
                            return;
                        }
                    }
                }

//          /* 启动WIFI */
//                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//                switch (wifiManager.getWifiState()) {
//                    case WifiManager.WIFI_STATE_DISABLED:
//                        wifiManager.setWifiEnabled(true);
//                        break;
//                    default:
//                        break;
//                }

            }

        }, 1000);
    }

    public void destory()
    {

            context.unregisterReceiver(bluetoothReceiver);

    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值