BluetoothSocket预热时间?

时间:2017-01-30 23:52:38

标签: android bluetooth

我目前在BT服务器上使用以下代码:

BluetoothSocket clientSocket = serverSocket.accept();
Log.i(TAG, "slave: " + clientSocket.getRemoteDevice().getName() + " " +
    clientSocket.getRemoteDevice().getAddress() + " connected!");

try {
   Thread.sleep(300); // <—— Why??
} catch (InterruptedException e) {
   e.printStackTrace();
}
PrintWriter bw = new PrintWriter(
    new OutputStreamWriter(clientSocket.getOutputStream()));
bw.println(System.currentTimeMillis());
bw.flush();
bw.close();
clientSocket.close();

正如您所看到的,我必须在Thread.sleep和第一次写入之间放置accept(),否则我的客户端将无法读取该行,从而输出以下错误:

W/System.err: java.io.IOException: bt socket closed, read return: -1
W/System.err:     at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:517)
W/System.err:     at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)

是什么原因?有没有替代硬编码等待时间?

客户端代码的重要部分:

bluetoothSocket.connect(); // will block until a connection is established or failed
    BufferedReader br = null;
    try {
        if (bluetoothSocket.isConnected()) {
            br = new BufferedReader(new InputStreamReader(bluetoothSocket.getInputStream()));
            String line = br.readLine();
            long remoteTime = Long.parseLong(line);
            long offset = System.currentTimeMillis() - remoteTime;
            Log.e(TAG, "Offset=" + offset);
            return offset;
        } else throw new Exception("link not created");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (br != null) br.close();
        if (bluetoothSocket != null)
            bluetoothSocket.close();
    }

0 个答案:

没有答案