将BT置于可发现模式并接受Xamarin Droid中的SPP连接

时间:2018-05-16 20:04:55

标签: android xamarin xamarin.forms bluetooth xamarin.android

这是我第一次使用蓝牙与Xamarin。
我需要激活"可发现模式"在我的应用程序中,然后接受来自外部主机设备的传入连接。 我已经阅读了一些文档但我无法理解如何实现它。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

我找到了方法..

首先打开将蓝牙置于发现模式的意图......

var intent = new Intent(BluetoothAdapter.ActionRequestDiscoverable);
StartActivityForResult(intent, 0);

然后,使用ListenUsingInsecureRfcommWithServiceRecord将BT置于聆听模式:

class BluetoothThread : Java.Lang.Thread
{
  BluetoothServerSocket _btServerSocket;
  BluetoothSocket       _btSocket;
  Stream                _inStream;
  Stream                _outStream;

  private static Java.Util.UUID uuid = Java.Util.UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");

  public event EventHandler<String> OnStringReceived;

  public bool Cancel { get; set; } = false;

  public override void Run()
  {
    byte[] buffer = new byte[1024];
    int bytes;
    string _ReceivedStr;

    try
    {
      _btServerSocket =  
        BluetoothAdapter.DefaultAdapter.ListenUsingInsecureRfcommWithServiceRecord("Test.Droid", uuid);

      try
      {
        _btSocket = _btServerSocket.Accept();

        if (_btServerSocket != null)
          Log.Info("BluetoothThread", "CONNECTION SUCCEED!");

        _inStream = _btSocket.InputStream;
        _outStream = _btSocket.OutputStream;
      }
      catch (Java.IO.IOException e)
      {
        Log.Error("BluetoothThread", "accept() failed", e);
      }

      while (!Cancel)
      {
        // Read from the InputStream
        bytes = _inStream.Read(buffer, 0, buffer.Length);
        _ReceivedStr = Encoding.ASCII.GetString(buffer);

        OnStringReceived?.Invoke(this, _ReceivedStr);

        Log.Info("BluetoothThread", $"RECEIVED: {_ReceivedStr}");
      }

    }
    catch (Java.IO.IOException e)
    {
      Log.Error("BluetoothThread", "listen() failed", e);
    }

  }
}