【发布时间】:2013-11-15 19:59:01
【问题描述】:
您好,我正在尝试创建一个 Android 应用程序,该应用程序将连接到我想要向其发送数据的 Blue SMiRF 蓝牙加密狗。我已经阅读了开发人员页面并查看了多个不同的示例,但是我目前在创建与套接字的连接时遇到了麻烦。代码的蓝牙部分几乎来自我能够找到的一个示例。当尝试连接到蓝牙加密狗时,应用程序会强制关闭,因为我没有正确处理一些错误。但是,我也尝试使用该应用程序仅连接到另一台 PC,并且由于某种原因,即使在运行该应用程序之前我已经通过蓝牙设置与设备配对,连接也无法正确建立。我在下面发布了一些更重要的代码,说明我认为我的问题可能出在哪里。任何帮助将不胜感激,如果我应该发布任何其他代码,请告诉我。
protected void connect(BluetoothDevice device) {
//BluetoothSocket socket = null;
try {
//Create a Socket connection: need the server's UUID number of registered
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
socket.connect();
Log.d("EF-BTBee", ">>Client connectted");
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new byte[] { (byte) 0xa0, 0, 7, 16, 0, 4, 0 });
new Thread() {
public void run() {
while(true)
{
try {
Log.d("EF-BTBee", ">>Send data thread!");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(new byte[] { (byte) 0xa2, 0, 7, 16, 0, 4, 0 });
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
}
}
};
}.start();
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
} finally {
if (socket != null) {
try {
Log.d("EF-BTBee", ">>Client Close");
socket.close();
finish();
return ;
} catch (IOException e) {
Log.e("EF-BTBee", "", e);
}
}
}
}`
我也尝试过使用
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
socket = (BluetoothSocket) m.invoke(device, 1);
而不仅仅是上面的“socket =”行,但仍然没有成功。
【问题讨论】:
-
感谢您的评论。不幸的是,它仍然无法正确创建蓝牙套接字连接。
-
重读过(一定是一开始就读错了),但能够正确创建蓝牙套接字,但实际连接仍然有问题。