我想做的就是向第一个传入的RFCOMM蓝牙连接发送“hello”,然后退出。我的代码适用于诺基亚N73,但不适用于诺基亚E52等更现代的设备。在诺基亚E52中,应用程序暂停:
streamConnectionNotifier.acceptAndOpen();
以下是代码:
所有代码都在我的线程的run()方法中:
public class BTTest extends Thread {
public void run() {
...
}
}
我首先将我的蓝牙设备设置为可发现:
try {
LocalDevice localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
} catch (BluetoothStateException exception) {
System.out.println(exception.toString());
}
然后,我准备我的服务器套接字:
StreamConnectionNotifier streamConnectionNotifier = null;
try {
String url = "btspp://localhost:" + new UUID(0x1101).toString() + ";name=SampleServer";
streamConnectionNotifier = (StreamConnectionNotifier)Connector.open(url);
if (streamConnectionNotifier == null) {
System.out.println("Error: streamConnectionNotifier is null");
return;
}
} catch (IOException exception) {
System.out.println(exception.toString());
}
然后,我等待传入的RFCOMM蓝牙连接:
StreamConnection streamConnection = null;
try {
System.out.println("Waiting for incoming connection...");
streamConnection = streamConnectionNotifier.acceptAndOpen();
if (streamConnection == null) {
System.out.println("Error: streamConnection is null");
} else {
System.out.println("Connection received.");
}
} catch (IOException exception) {
System.out.println(exception.toString());
}
有一次,我得到StreamConnection对象,发送“hello”然后关闭连接:
try {
OutputStream out = streamConnection.openOutputStream();
String s = "hello";
out.write(s.getBytes());
out.flush();
streamConnection.close();
} catch (IOException exception) {
System.out.println(exception.toString());
}
在诺基亚N73中,我收到“已收到连接”。在日志上,我在客户端收到“你好”。但在诺基亚E52,诺基亚5230,诺基亚E71上,该应用程序在streamConnectionNotifier.acceptAndOpen()之后挂起。
有没有人有想法?如果您需要更多信息,请说明。
答案 0 :(得分:0)
您应该指定自己的128位UUID(使用0x1101
或类似工具),而不是使用SPP UUID(uuidgen
)。在应用程序挂起的手机上,可能还有另一个SPP服务正在运行。