我试图通过蓝牙Android平板电脑,并用BlueSmirf蓝牙适配器一个Arduino之间的通信正常工作。 在我的Android代码中,我首先检查我正在寻找的已配对设备的列表。如果它不在那里,我开始发现。 这两种可能性都适用于BlueSmirf上的状态LED变为绿色表示成功连接的点。 但是,只有在我启动应用程序之前设备未配对,我也能够通过蓝牙发送/接收数据。如果之前配对了设备,则连接建立更可靠且速度更快,但无法发送或接收数据。 你知道为什么吗?提前谢谢了!蓝牙连接(安卓/ 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();
}
}
UPDATE:
我现在也试图取代这一部分:
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")
Stil l同样的问题。
我也尝试运行整个连接过程,而不只是运行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);
}
}
};
对不起,是一个java纳粹,但为了使代码有点更具可读性对我们来说,尽量坚持到Java命名约定。 http://java.about.com/od/javasyntax/a/nameconventions.htm – frogmanx
是的你是对的,这看起来很混乱。我会编辑它... – Huxley
嗯有人吗?我会很感激只是一个小提示。 – Huxley