我正在尝试通过蓝牙从我的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:传输端点未连接
怎么了?
答案 0 :(得分:0)
我发现使用安全连接解决了我的问题。但在您的情况下,您需要致电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();