我正在尝试通过蓝牙在安卓平板电脑和带有BlueSmirf蓝牙加密狗的Arduino之间进行通信。在我的Android代码中,我首先检查已经配对的设备列表,以找到我正在寻找的设备。如果它不在那里,我就会开始发现。当BlueSmirf上的状态指示灯变为绿色以指示连接成功时,这两种情况都会起作用。但只有在我启动应用程序之前设备没有配对的情况下,我才能通过蓝牙发送/接收数据。如果设备以前是配对的,则建立连接更可靠、更快,但无法发送或接收任何数据。你知道为什么会这样吗?首先要感谢大家!
相关代码如下:
public void connect() {
// I know I should be using an intent here...
while (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
}
pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("FireFly-8AAD")) {
mDevice = device;
}
}
}
if (mDevice == null) {
// BroadcastReceiver registered with IntentFilter(BluetoothDevice.ACTION_FOUND)
registerReceiver(mReceiver, find);
if (!bluetoothAdapter.isDiscovering ()) {
bluetoothAdapter.startDiscovery();
}
}
while (mDevice == null) {
// Wait for BroadcastReceiver to find the device and
// connect
}
if (mDevice != null) {
// Create socket connection in a new thread
Connect connection = new Connect();
new Thread(connection).start();
}
while (mSocket == null) {
// Wait for successfull socket connection
}
if (mSocket != null) {
// Get input/ouputstream
Communication communicate = new Communication();
new Thread(communicate).start();
}}
更新:
我现在也尝试替换这一部分:
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("FireFly-8AAD")) {
mDevice = device;
}
}
}有了这个:
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("FireFly-8AAD")) {
mDevice = bluetoothAdapter.getRemoteDevice(device.getAddress());
}
}
}正如这里所建议的:Android Bluetooth accept() / connect() with already paired devices
但它还是不起作用。
更新2:
我换掉了
device.getName().equals("FireFly-8AAD")使用
device.getAddress().equals("MAC-Address here")仍然是同样的问题。
我还尝试在一个新线程中运行整个连接过程,而不是只在它们自己的线程中运行socket.connect()和socket.getInput/OuputStream,但这也没有帮助。
更新3:
我想如果我还提供建立连接的代码,我可以发送/接收数据,这可能会有所帮助:
private class mBroadcastReceiver extends BroadcastReceiver {
private String discoveredDeviceName;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
}
if (discoveredDeviceName.equals("FireFly-8AAD")) {
bt_device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
}
}
};发布于 2014-06-18 03:00:45
使用早期配对的bluesmirf,我在连接()之前执行"cancelDiscovery()“,如下所示:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = adapter.getRemoteDevice(macAddr);
if (adapter.isDiscovering())
adapter.cancelDiscovery();
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
btSocket = (BluetoothSocket) m.invoke(device, 1);但有时,蓝牙模块在关闭数据流和插座后仍保持连接,而绿色的led在平板电脑关机后仍保持激活状态。这很奇怪,我认为是硬件问题。
https://stackoverflow.com/questions/17459490
复制相似问题