BluetoothSocket.Connect超时

时间:2012-01-26 22:40:20

标签: bluetooth xamarin.android

我正在把头发拉出来。我在网上搜索了一个工作示例,但却找不到一个。

我正在尝试连接蓝牙设备。原始代码适用于Java版本。

一切正常,直到调用Connect(),然后一切都会挂起。我需要能够向蓝牙设备发送和接收数据,我的理解是必须首先调用Connect()。

代码:

// first, check that blue tooth is available
using (BluetoothAdapter btAdapter = BluetoothAdapter.DefaultAdapter)
{
    // if no adapter, then exit
    if (btAdapter == null)
    {
    // show toast message
    Toast.MakeText(m_Context, "Bluetooth is not turned on", ToastLength.Long).Show();

    // exit
    return false;
    }

    // we found an adapter, now get the list of attached devices
    foreach (BluetoothDevice device in btAdapter.BondedDevices)
    {
    // skip if not a P25
    if (!device.Name.ToLower().Contains("p25"))
        continue;

    BluetoothDevice mdevice = btAdapter.GetRemoteDevice(device.Address);

    IntPtr createRfcommSocket = JNIEnv.GetMethodID(
            mdevice.Class.Handle,
            "createRfcommSocket",
            "(I)Landroid/bluetooth/BluetoothSocket;");
    IntPtr socket = JNIEnv.CallObjectMethod(
        mdevice.Handle,
        createRfcommSocket,
        new JValue(1));

    // we found the device, confirm it's actually paired and turned on
    using (BluetoothSocket NewSocket = new Java.Lang.Object(socket).JavaCast<BluetoothSocket>())
    {
        try
        {
        // skip if nothing created
        if (NewSocket == null)
            continue;

        // connect
        NewSocket.Connect();

        // get the output stream
        NewSocket.OutputStream.Close();

        // close the socket
        NewSocket.Close();
        }

        catch (Exception excep)
        {
        Log.Error("DeviceLink", excep.Message);
        continue;
        }
    }
     }
}

2 个答案:

答案 0 :(得分:0)

Hy,对不起我的英语不好,我相信你开发的用BlueBamboo,我在Bluebamboo PM25中使用Monodroid进行打印也有很多问题,这样就解决了,创建了一个包含3个全局的新类:

            public BluetoothAdapter Adapter;
            public BluetoothDevice RemoteDevice;
            public BluetoothSocket Socket;

现在在班级的建设者

            Adapter = BluetoothAdapter.DefaultAdapter;

            if (Adapter == null) throw new NotSupportedException("Dispositivo sem suporte a bluetooth");
            if (!Adapter.IsEnabled) Adapter.Enable();

            foreach (var device in Adapter.BondedDevices)
            {
                if (!device.Name.ToLower().Contains("p25")) continue;

                RemoteDevice = Adapter.GetRemoteDevice(device.Address);
                Socket = RemoteDevice.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805F9B34FB"));

                if (Socket == null) continue;

                Socket.Connect();
                break;


            }

实例仅在您的Activity中使用此类,在使用后,只关闭SOCKET或在您的类中实现IDisposable。

         public void Dispose()
         {
              Socket.Close();
         }

快乐!!!!

答案 1 :(得分:0)

我知道这篇文章已经过时了,我在这里寻找其他东西,但我遇到了同样的问题,为我解决'挂起'问题是在与UI线程不同的线程上运行连接部分然后更新带有结果的UI线程。这对我有用..(顺便说一句,我使用Monodroid进行C#)

 private void connectBTwThread()
    {
        new Thread(new ThreadStart(() =>
        {
            TextView txtList = FindViewById<TextView>(Resource.Id.devicesList);

            #region Connect routine

            BluetoothSocket btSockets = bth.BondedDevices.Where(d => d.Name.ToUpper().Contains("JVC")).Single()
                .CreateRfcommSocketToServiceRecord(_uuid);

            try
            {
                RunOnUiThread(() =>
                {
                    txtList.Text += System.Environment.NewLine;
                    txtList.Text += "Attempting to Connect to " + btSockets.RemoteDevice.Name
                        + System.Environment.NewLine;
                });

                btSockets.Connect();

                if (btSockets.IsConnected)
                    RunOnUiThread(() => { txtList.Text += "Connected to " + btSockets.RemoteDevice.Name; });

                btSockets.Close();
            }
            catch (IOException e)
            {
                RunOnUiThread(() => { txtList.Text += "BT Connect Failed: " + e.Message + System.Environment.NewLine; });
                try
                {
                    btSockets.Close();
                }
                catch (IOException closeException)
                {
                    return;
                }
            }
            #endregion

        })).Start();
    }

我发布它以回馈SO社区,希望有人能从中受益...