BluetoothServerSocket未从Accept方法返回

时间:2015-11-26 09:41:49

标签: android multithreading bluetooth block bluetooth-socket

BluetoothServerSocketInstance.accept()没有返回任何内容 下一步没有执行

线程块在同一个地方 我见过很多类似的问题但很遗憾没有一个对我有帮助

我正在创建像这样的接受线程

private class AcceptThread extends Thread {
    // The local server socket

    private String mSocketType;
    boolean isRunning = true;
    private BluetoothServerSocket mmServerSocket;

    public AcceptThread(boolean isAndroid) {
        BluetoothServerSocket tmp = null;

        // Create a new listening server socket
        try {
            if (isAndroid)
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(
                        NAME_SECURE, UUID_ANDROID_DEVICE);
            else
                tmp = mAdapter.listenUsingRfcommWithServiceRecord(
                        NAME_SECURE, UUID_OTHER_DEVICE);
        } catch (IOException e) {
        }
        mmServerSocket = tmp;
    }

    public void run() {
        setName("AcceptThread" + mSocketType);
        BluetoothSocket socket = null;

        // Listen to the server socket if we're not connected
        while (mState != BluetoothState.STATE_CONNECTED && isRunning) {

            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception

                if (mmServerSocket != null)
                    socket = mmServerSocket.accept();

            } catch (IOException e) {
                break;
            }

            // If a connection was accepted
            if (socket != null) {
                synchronized (BluetoothService.this) {
                    switch (mState) {
                    case BluetoothState.STATE_LISTEN:
                    case BluetoothState.STATE_CONNECTING:
                        // Situation normal. Start the connected thread.
                        connected(socket, socket.getRemoteDevice(),
                                mSocketType);
                        break;
                    case BluetoothState.STATE_NONE:
                    case BluetoothState.STATE_CONNECTED:
                        // Either not ready or already connected. Terminate
                        // new socket.
                        try {
                            socket.close();
                        } catch (IOException e) {
                        }
                        break;
                    }
                }
            }
        }
    }

    public void cancel() {
        try {
            mmServerSocket.close();
            mmServerSocket = null;
        } catch (IOException e) {
        }
    }

    public void kill() {
        isRunning = false;
    }
}

0 个答案:

没有答案