c #Android - BluetoothServerSocket.Accept没有结果

时间:2017-08-03 16:59:25

标签: c# android bluetooth server connection

由于此代码基于此documentation

,我正在尝试收听传入的蓝牙连接
public void WaitForConnection()
{
    BluetoothServerSocket serverSocket = null;
    BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
    if (adapter == null)
        throw new Exception("No Bluetooth adapter found");
    if (!adapter.IsEnabled)
        throw new Exception("Bluetooth adapter is not enabled");

    // Create a new listening server socket
    try
    {
        serverSocket = adapter.ListenUsingRfcommWithServiceRecord("MindCam", UUID.FromString(Ev3UUID));
    }
    catch (Java.IO.IOException e)
    {
        Console.WriteLine("Error listening connection: " + e.Message);
    }

    Task t = Task.Factory.StartNew(() =>
    {
        while (true)
        {
            try
            {
                _socket = serverSocket.Accept();
            }
            catch (IOException e)
            {
                Console.WriteLine("Socket's accept() method failed");
                break;
            }

            if (_socket != null)
            {
                // A connection was accepted.
                serverSocket.Close();
                Console.WriteLine("Connection accepted");
                break;
            }
        }
    });
}

我在活动开始时调用此方法。我调试它,似乎代码执行直到" serverSocket.Accept()",即使没有等待,代码也不再执行。之后,即使我尝试从蓝牙设备(Mindstorms砖)到Android设备建立连接,也不会检测到它,并且此线程不会继续...

为什么这不起作用?

提前致谢。

0 个答案:

没有答案