Xamarin蓝牙接收数据不起作用

时间:2019-03-20 20:30:46

标签: xamarin android-bluetooth

从HC-05蓝牙模块接收数据时出现问题。从移动设备发送数据到模块工作正常,但我不知道如何从模块接收数据。我认为包含侦听器功能的线程会出现问题。 感谢您的帮助

代码如下:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Bluetooth;
using Microcharts;
using Entry = Microcharts.Entry;
using Microcharts.Droid;
using SkiaSharp;
using System.Linq;
using System.Collections.Generic;


namespace BLE
{
    [Activity(Label = "BLE", MainLauncher = true)]
    public class MainActivity : Activity
    {

        BluetoothConnection myConnection = new BluetoothConnection();


        protected override void OnCreate(Bundle savedInstanceState)
        {
            var metrics = Resources.DisplayMetrics;
            var width = metrics.WidthPixels;
            var height = metrics.HeightPixels;
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            Button buttonConnect = FindViewById<Button>(Resource.Id.button1);
            Button buttonDisconnect = FindViewById<Button>(Resource.Id.button2);

            buttonConnect.LayoutParameters.Width = Convert.ToInt32(width * 0.5);
            buttonDisconnect.LayoutParameters.Width = Convert.ToInt32(width * 0.5);

            TextView connected = FindViewById<TextView>(Resource.Id.textView1);

            BluetoothSocket _socket = null;

            System.Threading.Thread listenThread = new System.Threading.Thread(listener);
            listenThread.Abort();

            buttonConnect.Click += delegate
            {

                try
                {
                    buttonDisconnect.Enabled = false;
                    buttonConnect.Enabled = true;
                    listenThread.Abort();

                    myConnection.thisDevice.Dispose();

                    myConnection.thisSocket.OutputStream.WriteByte(187);
                    myConnection.thisSocket.OutputStream.Close();

                    myConnection.thisSocket.Close();

                    myConnection = new BluetoothConnection();
                    _socket = null;

                    connected.Text = "Disconnected!";
                }
                catch { }

                listenThread.Start();

                myConnection = new BluetoothConnection();
                myConnection.thisSocket = null;
                _socket = null;

                myConnection.getAdapter();

                myConnection.thisAdapter.StartDiscovery();

                try
                {

                    myConnection.getDevice();
                    myConnection.thisDevice.SetPairingConfirmation(false);
                    myConnection.thisDevice.Dispose();
                    myConnection.thisDevice.SetPairingConfirmation(true);
                    myConnection.thisDevice.CreateBond();


                }
                catch (Exception deviceEX)
                {
                }

                myConnection.thisAdapter.CancelDiscovery();


                _socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));

                myConnection.thisSocket = _socket;

                try
                {



                    myConnection.thisSocket.Connect();

                    connected.Text = "Connected!";
                    buttonDisconnect.Enabled = true;
                    buttonConnect.Enabled = false;

                    if (listenThread.IsAlive == false)
                    {
                        listenThread.Start();
                    }

                }
                catch (Exception CloseEX)
                {

                }


            };

            buttonDisconnect.Click += delegate
            {

                try
                {
                    buttonConnect.Enabled = true;
                    listenThread.Abort();

                    myConnection.thisDevice.Dispose();

                    myConnection.thisSocket.OutputStream.WriteByte(187);
                    myConnection.thisSocket.OutputStream.Close();

                    myConnection.thisSocket.Close();

                    myConnection = new BluetoothConnection();
                    _socket = null;

                    connected.Text = "Disconnected!";
                }
                catch { }
            };


            void listener()
            {
                TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
                while (true)
                {
                    try
                    {
                        byte[] buffer = new byte[1];
                        myConnection.thisSocket.InputStream.Read(buffer, 0, 1);
                        myConnection.thisSocket.InputStream.Close();
                        String dispString = System.Text.ASCIIEncoding.Default.GetString(buffer);
                        RunOnUiThread(() =>
                        {
                        //readTextView.Text = dispString;
                        System.Console.WriteLine(dispString);
                        });
                    }
                    catch (Java.IO.IOException)
                    {
                        RunOnUiThread(() =>
                        {
                            readTextView.Text = string.Empty;
                        });
                        break;

                    }
                }
            }
        }

        public class BluetoothConnection
        {

            public void getAdapter() { this.thisAdapter = BluetoothAdapter.DefaultAdapter; }
            public void getDevice() { this.thisDevice = (from bd in this.thisAdapter.BondedDevices where bd.Name == "HC-05" select bd).FirstOrDefault(); }

            public BluetoothAdapter thisAdapter { get; set; }
            public BluetoothDevice thisDevice { get; set; }

            public BluetoothSocket thisSocket { get; set; }

        }

    }
}

` 感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我不知道此事件在buttonConnect.Click事件中的作用

try
   {
      buttonDisconnect.Enabled = false;
      buttonConnect.Enabled = true;
      listenThread.Abort();
      myConnection.thisDevice.Dispose();
      myConnection.thisSocket.OutputStream.WriteByte(187);
      myConnection.thisSocket.OutputStream.Close();
      myConnection.thisSocket.Close();
      myConnection = new BluetoothConnection();
      _socket = null;
      connected.Text = "Disconnected!";
   }
   catch { }

通常会收到这样的数据(简单用法):

System.Threading.Thread listenThread = new System.Threading.Thread(Listener);

buttonConnect.Click += delegate {
   myConnection = new BluetoothConnection();
   myConnection.getAdapter();
   myConnection.getDevice();
   _socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
   myConnection.thisSocket = _socket;
   myConnection.thisSocket.Connect();
   listenThread.Start();
   }

 private void Listener()
    {
        while (true)
        {
            try
            {
                byte[] buffer = new byte[1];
                TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
                myConnection.thisSocket.InputStream.Read(buffer, 0, 1);
                myConnection.thisSocket.InputStream.Close();
                String dispString = System.Text.ASCIIEncoding.Default.GetString(buffer);
                RunOnUiThread(() =>
                {
                    readTextView.Text = dispString;
                    System.Console.WriteLine(dispString);
                });
            }
            catch (Java.IO.IOException)
            {
                TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
                RunOnUiThread(() =>
                {
                    readTextView.Text = string.Empty;
                });
                break;
            }
        }
    }
}


public class BluetoothConnection
{
    public void getAdapter() { this.thisAdapter = BluetoothAdapter.DefaultAdapter; }
    public void getDevice() { this.thisDevice = (from bd in this.thisAdapter.BondedDevices where bd.Name == "hc-05" select bd).FirstOrDefault(); }

    public BluetoothAdapter thisAdapter { get; set; }
    public BluetoothDevice thisDevice { get; set; }

    public BluetoothSocket thisSocket { get; set; }
}