java捕获超时异常代码,获取java.io.IOException异常:读取失败,插座有可能在BluetoothSocket.connect关闭或超时()...

I'm trying to write a code that only connect to my (for now) only paired device on my Nexus 7 running Android 4.4 KitKat. No matter how many thing I have tried, I still get this error. This is the last code I have tried, which seems to be doing everything I've seen people report as successful.

Can anybody point me to what I'm doing wrong?

BluetoothManager bluetoothManager =

(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);

BluetoothAdapter adapter = bluetoothManager.getAdapter();//BluetoothAdapter.getDefaultAdapter();

if (!adapter.isEnabled()) {

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

}

BluetoothDevice bt = adapter.getBondedDevices().iterator().next();

BluetoothDevice actual = adapter.getRemoteDevice(bt.getAddress());

String str = "";

for(BluetoothDevice bd : adapter.getBondedDevices()) {

str += bd.getName() + "\n";

}

str+= actual;

textView.setText(str);

BluetoothSocket socket = actual.createInsecureRfcommSocketToServiceRecord(MY_UUID);

adapter.cancelDiscovery();

socket.connect();

PrintWriter out = new PrintWriter(socket.getOutputStream());

out.print(message);

out.flush();

解决方案

I had the exactly same error (IOException read failed socket might closed or timeout) with an ELM327 OBD bluetooth adapter.

UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

btDevice = btAdapter.getRemoteDevice(btDeviceAddress);

btAdapter.cancelDiscovery();

btSocket = btDevice.createRfcommSocketToServiceRecord(MY_UUID);

btSocket.connect();

The ELM327 would allow the first connection and send/receive correctly, but only once. Then, all later connections would fail with the IOException. To get it working again, I had to unpair the ELM327 from the OS, and then I'd be able to connect - just once! And the cycle repeats ...

The problem was solved as described in the post above - create an INSECURE socket.

btSocket = btDevice.createInsecureRfcommSocketToServiceRecord(MY_UUID);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值