代码之家  ›  专栏  ›  技术社区  ›  Barzo

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

  •  0
  • Barzo  · 技术社区  · 8 年前


    我需要在应用程序中激活“可发现模式”,然后接受来自外部主机设备的传入连接。 我读过一些文件,但我不太明白如何实施它。

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

    1 回复  |  直到 8 年前
        1
  •  0
  •   Barzo    8 年前

    我找到了路。。

    首先打开一个意图,将蓝牙置于发现模式。。。

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