首页 > 解决方案 > BluetoothAdapter.getBondedDevices 虽然已配对但返回零设备,为什么?

问题描述

我目前正在尝试编写一个使用蓝牙连接到设备并打开串行连接的 Android 应用程序。要连接到设备,我需要将设备传递给一些建立和维护连接的代码。我的问题是我似乎没有达到这一点,因为我的代码总是返回一个 NullPointer 作为设备。

我已经尝试调试代码,现在发现获取绑定设备的功能返回零设备。为了缓解这种情况,我确保蓝牙适配器存在并且已打开。我还确保在 android 菜单中连接了设备,并且我要建立连接的 android 设备已配对。

下面是应该识别并返回设备的代码:

public class BluetoothDeviceRecognition {
BluetoothDevice blDevice(BluetoothAdapter myBluetoothAdapter) {


    Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
    BluetoothDevice myDevice = null;
    if(pairedDevices.size() > 0){
        for (BluetoothDevice device : pairedDevices){
            if (device.getName().equals("ESP32_LED_Control")) {
                myDevice = device;

            }
        }
    }
    return myDevice;
}

这是应确保有蓝牙适配器的代码,如果不是这种情况,则应启用它:

    public void startBluetooth(){
    if(mBluetoothAdapter == null)
    {
        Log.d(TAG, "connectBluetooth: Does not have Bluetooth Capabilities");
        return;
    }
    if(!mBluetoothAdapter.isEnabled())
    {
        Log.d(TAG, "connectBluetooth: Enabling Bluetooth");
        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivity(enableBTIntent);
    }
}

这是启动上述代码的代码:

        connect.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            try{
                startBluetooth();
                BluetoothDevice myDevice = mBluetoothDevice.blDevice(mBluetoothAdapter);

                connectBluetooth(myDevice, MY_UUID_INSECURE);
            }
            catch(NullPointerException e){
                Log.d(TAG, "connectBluetooth: Bluetooth Device cannot be Null");
                sent.setText("Error, Bluetooth Device cannot be Null");
            }


        }
    });

在第一个代码片段的 if 循环开头设置断点时,我希望pairedDevices 的大小大于0,但pairedDevices 的实际大小为零。

编辑:

我的清单文件:

<?xml version="1.0" encoding="utf-8"?>

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

我的目标 SDK 应该是 21。

编辑:所以我并没有真正解决这个问题,而是使用了不同的方法。我不是寻找与我的设备配对的设备,而是寻找当前在我附近发现的设备。使用此代码:https ://github.com/mitchtabian/Sending-and-Receiving-Data-with-Bluetooth

标签: javaandroidandroid-bluetooth

解决方案


在调用 mBluetoothDevice.blDevice(mBluetoothAdapter) 之前,您必须确保蓝牙已打开。所以你只需要使用startActivityForResult(enableBTIntent)来启用蓝牙并从onActivityResult()接收结果,一旦你收到用户打开蓝牙的reslut,你就可以调用mBluetoothDevice.blDevice(mBluetoothAdapter)。


推荐阅读