Android实现蓝牙的搜索,配对(不需要输入PIN,自动匹配),连接,通信

本文详细介绍了在Android上实现蓝牙搜索、自动配对、连接和通信的步骤。包括设置蓝牙权限,获取蓝牙适配器,动态注册广播接收器以监听蓝牙设备状态,利用ClsUtils进行自动配对,通过接口实现广播与Activity之间的通信,以及初始化BluetoothService进行数据发送和接收。此外,还提供了结束连接和通信的处理方法。
摘要由CSDN通过智能技术生成

目录

一、蓝牙设置权限

需要在AndroidManifest.xml配置获得蓝牙权限。
按照SDK说明需要下面两个权限就可以进行蓝牙的开发。

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

在android6.0之后为了更好的保护用户的数据安全,所有需要访问硬件唯一标识符的地方都需要申请位置权限,也就是需要申请以下权限

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

二、蓝牙搜索

1.首先需要获得蓝牙适配器。
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
2.判断蓝牙是否打开,然后请求打开蓝牙
private void openBlueTooth() {
        if (!mBluetoothAdapter.isEnabled()) {
            //通过这个方法来请求打开我们的蓝牙设备
           Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
           startActivityForResult(intent,BLUETOOTH_RESPONSE);
        }
    }

通过这个方法可以判断是否允许打开蓝牙,然后进行下面相应的操作

case BLUETOOTH_RESPONSE:
    if(resultCode == RESULT_OK){
        //获得蓝牙权限成功
        //需要再写一次,oncreate里的下面的方法无法执行
        duringDialog("正在连接蓝牙!");
        //搜索蓝牙
        searchBlueTooth();
     }else if(resultCode == RESULT_CANCELED){
        //获得蓝牙权限失败
        toast(ControlParkingActivity.this,"蓝牙权限获取失败,请打开蓝牙!");
     }
     break;
3.搜索蓝牙

如果已经打开蓝牙上面的搜索蓝牙不会执行,所以还需在onCreate方法中写搜索方法

        //请求判断蓝牙是否提前打开
        //如果没有提前打开则不会执行这句,执行openBluetooth的响应结果
        //如果提前打开则执行下面
        if(mBluetoothAdapter.isEnabled()){
            duringDialog("正在连接蓝牙!");
            searchBlueTooth();
        }

搜索蓝牙方法如下:

//搜索蓝牙设备
        private void searchBlueTooth() {
        //判断蓝牙是否已经绑定
        if(isBond()){
            Log.d(TAG,"蓝牙已经绑定");
            //已经绑定,直接连接蓝牙
            Log.d(TAG,device.getName() + "1");

        }else{
            Log.d(TAG,"搜索蓝牙中");
            //搜索蓝牙设备
            mBluetoothAdapter.startDiscovery();
        }
    }

三、蓝牙配对

蓝牙配对是通过广播接收器,搜索附近蓝牙设备,通过判断设备的address和name来判断是否为目标设备。之后利用ClsUtils工具类实现自动匹配蓝牙设备的功能。

1.动态注册广播接收器
        mBluetoothReceiver = new BluetoothReceiver();
        // 动态注册注册广播接收器。接收蓝牙发现讯息
        IntentFilter btFilter = new IntentFilter();
        btFilter.setPriority(1000);
        btFilter.addAction(BluetoothDevice.ACTION_FOUND);
        btFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        this.registerReceiver(mBluetoothReceiver,btFilter);

        //设置广播信息接口监听器
        mBluetoothReceiver.setReceiverMessageListener(this);

setPriority(1000):设置优先级,如果优先级比较低可能仍然会弹出输入pin的对话框
BluetoothDevice.ACTION_FOUND:发现设备时的action
BluetoothDevice.ACTION_PAIRING_REQUEST:当调用createBond()后就会发起BluetoothDevice.ACTION_PAIRING_REQUEST的广播

2.判断蓝牙设备是否为目标设备,并且创建绑定
        //获得action
        String action=intent.getAction();
        //获取设备
        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //获取搜索到的设备的名称和地址
        String name = device.getName();
        String address = device.getAddress();

        if(action.equals(BluetoothDevice.ACTION_FOUND))
        {
            Log.d(TAG, "发现设备:" + name);

            if ((name != null && btName.equals(name)) || btAddress.equals(address)) {
                //判断远程设备是否已经被绑定
                if(device.getBondState() != BluetoothDevice.BOND_BONDED){
                    Log.d(TAG, "发现目标设备,开始配对!");
                    try {
                        // 调用配对的方法,此方法是异步的,系统会触发BluetoothDevice.ACTION_PAIRING_REQUEST的广播
                        // 收到此广播后,设置配对的密码
                        ClsUtils.createBond(BluetoothDevice.class, device);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else{
                    //远程设备已经被绑定,取消搜索,返回信息

                }


            }
3.利用ClsUtils和事先获得的pin进行配对
else if(action.equals("android.bluetooth.device.action.PAIRING_REQUEST")){
            //createBond后再次得到action,就会等于PAIRING_REQUEST
            Log.d(TAG,"action2 = " + action);
            Log.d(TAG, "发现设备:" + device.getAddress() + " " + device.getName());

            if ((name != null && name.equals(btName)) || address.equals(btAddress)) {
                Log.d(TAG, "发现目标设备,开始配对!"
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,用于学习蓝牙开发的基本思想和方法。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值