Android蓝牙仅在第一次发送消息

时间:2015-12-25 19:57:52

标签: java android python bluetooth raspberry-pi

我需要从Raspberry PI向Android设备发送字符串消息。我只是第一次收到消息。之后它根本不起作用。我在Raspberry PI中使用PYTHON代码。第一次之后,它无法搜索正在运行该UUID的蓝牙设备。但是,如果我重新启动Android应用程序 - 它再次正常工作。我按建议here使用AcceptThread。我没有在我的应用程序中使用ConnectThread或ConnectedThread,因为我只需要传入消息。我是否需要在暂停或毁灭时关闭某些东西。或者,我是否需要做一些该页面中未提及的内容?

以下是代码:

private UUID MY_UUID = UUID.fromString("1e0ca4ea-299d-4335-93eb-27fcfe7fa848");
private AcceptThread acceptThread;

private class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        BluetoothServerSocket tmp = null;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord(TAG, MY_UUID);
        } catch (IOException e) { }
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }
            // If a connection was accepted
            if (socket != null) {
                // Do work to manage the connection (in a separate thread)
                manageConnectedSocket(socket);
                try {
                    mmServerSocket.close();
                }
                catch(IOException e){

                }
                break;
            }
        }
    }

    /** Will cancel the listening socket, and cause the thread to finish */
    public void cancel() {
        try {
            mmServerSocket.close();
        } catch (IOException e) { }
    }
}

我没有使用PI消息,只记录字符串。如上所述,它第一次起作用:

private void manageConnectedSocket(BluetoothSocket socket) {
    Log.i(TAG, "Hurray!! I am here");
    //acceptThread.cancel();
}

以下是Raspberry PI中的PYTHON代码:

import sys
import bluetooth

uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848"

service_matches = bluetooth.find_service( uuid = uuid )

if len(service_matches) == 0:
  print "couldn't find the BluetoothWithPi service"
  sys.exit(0)

first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]

print "connected to \"%s\" on %s" % (name, host)

sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((host, port))
sock.send("Hello from Raspberry PI!!")
sock.close()

首次显示'已连接到...'信息。第二次显示“无法找到......”#39;消息。

1 个答案:

答案 0 :(得分:0)

我们只需要在 manageConnectedSocket 块中添加一些代码。基本上我们需要取消acceptThread,如果不是null并重启服务:

AND posts_apex_po.post_type = 'apex_po'
AND posts_apex_po_payment.post_type = 'apex_po_payment'