简体   繁体   中英

Put BT in discoverable mode and Accept an SPP connection in Xamarin Droid

this is my first use of Bluetooth with Xamarin.
I need to activate the "discoverable mode" within my application and then accept the incoming connections from an external host device. I have read some docs but I cannot understand well how to implement it.

Could someone point me in the right direction?

I found the way..

First open an intent to put bluetooth in discovery mode...

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

Then, use ListenUsingInsecureRfcommWithServiceRecord to put BT in listening mode:

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);
    }

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM