0

上下文如下,我有一个 Android 应用程序,它在特定设备连接到它时启动一个活动,并发送一条代码消息。该设备不是另一个 android 应用程序,在这种情况下问题会容易得多。该设备是物联网设备 HC05。所以这个设备处于主模式,它尝试连接在这种情况下是从属的 android 应用程序。简而言之,android app必须是slave作为服务器才能接收连接,并且其他设备处于master模式,而且android app必须在广播接收器中检测设备,所以我不能直接使用使用BluetoothServerSocketaccept()方法,因为我无法运行线程。

我得到的最远的是实现此功能连接和断开蓝牙设备两次。所以,我的应用程序第一次启动广播接收器并检测到BluetoothDevice,它会阻止serverSocket.accept(). 然后,当我第二次断开并再次连接蓝牙设备时,我的应用程序成功返回了一个连接的套接字,我可以传输数据......是的!

这是我的代码

public class BluetoothConnectionReceiver extends BroadcastReceiver {
    private ConnectedThread mConnectedThread;
    private BluetoothSocket btSocket = null;

    public BluetoothConnectionReceiver(){}

    @Override
    public void onReceive(Context context, Intent intent) {
        //First time I connect the bluetooth device, this method is launched
        String action = intent.getAction();
        switch (action){
            case BluetoothDevice.ACTION_ACL_CONNECTED:
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                BluetoothSocket socket = null;
                try{
                    BluetoothServerSocket serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord("MyApp", MY_UUID_SECURE);
                    socket = serverSocket.accept(); //The first launch blocks 

                    //The second time, when I disconnect and connect again the device, the code continues properly and I can correctly transmit the data
                    serverSocket.close();
                    try{
                       mConnectedThread = new ConnectedThread(socket);
                       mConnectedThread.start();
                    }catch (IOException ex){
                       ex.printStackTrace();
                     }
               } catch (IOException ex){
                   ex.printStackTrace();
               }

public class ConnectedThread extends Thread {
    private InputStream mmInStream;
    private OutputStream mmOutStream;
    private BluetoothSocket mSocket;

    public ConnectedThread(BluetoothSocket socket) throws IOException{
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        tmpIn = socket.getInputStream();
        tmpOut = socket.getOutputStream();

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
        mSocket = socket;
    }

    // Other methods to receive and trasnmit data with the connected socket-
 }

问题是我只需要从设备连接一个连接就可以做到这一点,而无需连接和断开设备。类似于从设备创建一个连接的套接字(就像方法BluetoothServerSocket一样accept()),但是BluetoothDevice广播接收器给我的。

另外,我在设备设置为从模式的情况下独立启动与应用程序的连接没有问题

BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(BTMODULEUUID);
socket.connect();

device但是当我使用广播接收器给我的对象时,这对我不起作用。它抛出IOException: socket CONNECT read failed socket might closed or timeout可能是因为设备处于主模式。

我希望有人可以在我找不到任何商品的情况下帮助我。

4

0 回答 0