1

我要做的就是向第一个传入的 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() 之后挂起。

有人有想法吗?如果您需要更多信息,请说明。

4

1 回答 1

0

0x1101您应该指定自己的 128 位 UUID(使用uuidgen或类似工具) ,而不是使用 SPP UUID ( )。在应用程序挂起的手机上,可能有另一个 SPP 服务正在运行。

于 2011-01-02T17:17:43.483 回答