【发布时间】:2019-04-30 16:29:12
【问题描述】:
我目前正在尝试编写一个使用蓝牙连接到设备并打开串行连接的 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");
}
}
});
在第一个代码 sn-p 的 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
【问题讨论】:
-
你能展示你的 Manifest 和你指定的 Target Sdk 吗?
标签: java android android-bluetooth