我尝试编写仅连接到其他蓝牙设备的代码。我使用https://developer.android.com上提供的标准示例代码,但有些代码无法正常工作。它显示异常错误,如下所示: java.io.IOException:读取失败,socket可能关闭或超时,读取ret:-1 任何好友都可以帮助我: 我的代码是: btAdaptor.startDiscovery(); registerReceiver(bReceiver,新的IntentFilter(BluetoothDevice.ACTION_FOUND));
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the
// arrayAdapter
BTArrayAdapter.add(device.getName() + "\n"+ device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
Devices.add(device);
AlertDialog.Builder BT_Paired = new AlertDialog.Builder(MainActivity.this);
BT_Paired.setTitle("Available Device:");
BT_Paired.setAdapter(BTArrayAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, final int i) {
btAdaptor.cancelDiscovery();
BT_name = BTArrayAdapter.getItem(i);
AlertDialog.Builder BTpair = new AlertDialog.Builder(MainActivity.this);
BTpair.setMessage(BT_name);
BTpair.setTitle("Your Selected Item is:");
AlertDialog.Builder ok = BTpair.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
BluetoothDevice selectedDevice = Devices.get(i);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}
});
BTpair.show();
}
});
AlertDialog alertDialog = BT_Paired.create();
alertDialog.show();
}
}
};
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdaptor.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}