【问题标题】:Exception sending text string via bluetooth通过蓝牙发送文本字符串的异常
【发布时间】:2013-07-30 13:52:54
【问题描述】:

我正在尝试通过蓝牙将字符串从我的 Nexus S 发送到另一台 Android 设备。 代码如下:

public boolean onContextItemSelected(MenuItem item) {
  AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)
  item.getMenuInfo();
  if(item.getItemId() == 0)
  {
    BluetoothDevice selDev = pairedDevices.get(info.position);
    TelephonyManager tman = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    byte[] toSend = "a text".getBytes();
            try 
            {
                BluetoothSocket socket = selDev.createInsecureRfcommSocketToServiceRecord(
                      UUID.fromString("00001105-0000-1000-8000-00805F9B34FB"));
                OutputStream out = socket.getOutputStream();
                out.write(toSend);

                return true;
            } 
            catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
    }
    return true;
}

但我总是得到这个 IO 异常:java.io.IOException: Transport endpoint is not connected

怎么了?

【问题讨论】:

  • 你有没有先连接其他蓝牙设备?
  • 我有一个带有配对/绑定设备的列表视图,然后我必须向其中一个发送字符串
  • 你需要调用selDev .connect() 那实际上创建了套接字连接。但我的问题是它在那里失败了,我不知道为什么。

标签: android bluetooth


【解决方案1】:

我发现使用安全连接解决了我的问题。但在您的情况下,您需要调用 connect() 来启动连接。

//Just in case cancel any discovery as this slows everything down
selDev.CancelDiscovery();

//Try the secure method too. I found that worked for me.
BluetoothSocket socket = selDev.createInsecureRfcommSocketToServiceRecord(
                      UUID.fromString("00001105-0000-1000-8000-00805F9B34FB"));

socket.Connect();

OutputStream out = socket.getOutputStream();

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多