【问题标题】:Android: Bluetooth Serial (Com Port) communication with Android PhoneAndroid:与 Android 手机的蓝牙串行(Com 端口)通信
【发布时间】:2011-02-19 00:31:26
【问题描述】:

我正在尝试与蓝牙可编程微控制器通信。微控制器上的蓝牙设备(具体而言)在蓝牙串行 COM 端口号 4 上进行通信。

问题:我怎样才能让 Android 应用程序从这个 COM 端口(4 号)读取数据?

我知道 UUID 是一个众所周知的唯一 ID,适用于该设备,但我认为它与指定 COM 端口没有任何关系。

static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
btSocket = btDevice.createRfcommSocketToServiceRecord( myUUID);
btSocket.connect();
valid.append( btDevice.getName() + "\n" + btDevice.getAddress());
north.append("Socket Connected");
InputStream mmInStream = btSocket.getInputStream();
OutputStream mmOutStream = btSocket.getOutputStream();
byte[] buffer = new byte[10];
int bytes;
StringBuffer str = new StringBuffer();
while (true)                            {                               
     try {
    mmOutStream.write("a".getBytes());

        //Reads a # of bytes until the end of stream is reached
        bytes = mmInStream.read(buffer);
        //Transform to string
                str.append(buffer.toString()+"\t");                         //Clear the buffer
        Log.e("DATA", "THE DATA: "+ str.toString());
        south.setText(str.toString());
         str.delete(0,str.length());
       } catch (IOException e) {
        break;
} }}

【问题讨论】:

    标签: android bluetooth serial-port


    【解决方案1】:

    COM 端口仅存在于微控制器上,而不是连接到它的蓝牙设备。蓝牙设备甚至不知道微控制器用来连接它的 COM 端口。蓝牙设备与 micro 的连接是通过 TX 和 RX 线。它们连接到分配给特定 COM 端口的 micro 引脚上的事实与蓝牙设备无关且未知。

    【讨论】:

      【解决方案2】:

      我构建的自定义蓝牙设备遇到了这个问题。不要在连接线程中使用 createRfcommSocketToServiceRecord,而是尝试类似以下的操作:

          public ConnectThread(BluetoothDevice device) throws 
              SecurityException, NoSuchMethodException, IllegalArgumentException, 
                IllegalAccessException, InvocationTargetException {
                  mmDevice = device;
                  BluetoothSocket tmp = null;
      
                  // Force a BluetoothSocket for a connection with the
                  // given BluetoothDevice
      
                  Method m = mmDevice.getClass().getMethod("createRfcommSocket", 
                                 new Class[]{int.class});
      
              mmSocket = (BluetoothSocket)m.invoke(mmDevice, Integer.valueOf(1));
          }
      

      我的 mmDevice 是你的 btDevice。

      这会在未知设备和智能手机之间强制建立套接字连接。据我所知,Android 连接“非相似”设备存在问题。值得一试。

      【讨论】:

        猜你喜欢
        • 2014-12-22
        • 1970-01-01
        • 2016-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多