BluetoothSocket连接失败

时间:2016-07-13 08:47:01

标签: android bluetooth

我的演示只是决定在两部手机之间建立连接。但是当我的客户端试图调用bluetoothSocket.connect()时,它会抛出一条带有no route to host消息的IOException。我尝试了很多方法,但它并没有&# 39;工作。

这是关于AcceptThread和ConnectThread的代码(删除了一些不相关的代码以使其更简洁)

class AcceptThread extends Thread {

    private final BluetoothServerSocket mmServerSocket;
    BluetoothServerSocket tmp;

    public AcceptThread() {

        Method listenMethod = null;
        try {
            listenMethod = bluetoothAdapter.getClass().getMethod("listenUsingRfcommOn",new Class[]{int.class});
        } 
        try {
            tmp = ( BluetoothServerSocket) listenMethod.invoke(bluetoothAdapter, new Object[]{30});
        } 
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        while (isAcceptRun) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                Log.i(TAG, "run: AB "+e);
                break;
            }
            if (socket != null) {
                try {
                    mmServerSocket.close();
                }
                break;
            }
        }
    }
}

class ConnectThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {

        BluetoothSocket tmp = null;
        mmDevice = device;
        Method m = null;
        try {
            m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
        } 
        try {
            tmp = (BluetoothSocket) m.invoke(device, Integer.valueOf(30));
        } 
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        bluetoothAdapter.cancelDiscovery();

        try {
            mmSocket.connect();
        } catch (IOException connectException) {
            try {
                mmSocket.close();
            } catch (IOException closeException) {
            }
            return;
        }
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

1 个答案:

答案 0 :(得分:0)

在Google的BluetoothChat示例中,BluetoothSocket由以下人员构建:

private static final UUID MY_UUID_SECURE =
            UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE =
            UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");

if (secure) {
   tmp = device.createRfcommSocketToServiceRecord(
            MY_UUID_SECURE);
} else {
   tmp = device.createInsecureRfcommSocketToServiceRecord(
            MY_UUID_INSECURE);
}