发现Xamarin.Android中的蓝牙设备列表

时间:2018-04-17 08:06:39

标签: c# android xamarin bluetooth

在多个论坛和网站讲述如何发现蓝牙设备(配对或未配对)之后,我写下了这段代码。

class MainActivity: Activity
{
    BluetoothAdapter btAdapter;
    static ArrayAdapter<string> newDevicesArrayAdapter;
    public static List<string> mDeviceList = new List<string>();
    DeviceDiscoveredReceiver receiver;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        receiver = new DeviceDiscoveredReceiver(this);
        IntentFilter filter = new IntentFilter(BluetoothDevice.ActionFound);
        RegisterReceiver(receiver, filter);
        btAdapter = BluetoothAdapter.DefaultAdapter;
    }

    class DeviceDiscoveredReceiver : BroadcastReceiver
    {
        Activity mainActivity;
        public DeviceDiscoveredReceiver(Activity activity)
        {
            this.mainActivity = activity;
        }
        public override void OnReceive(Context context, Intent intent)
        {
            String action = intent.Action;
            if (BluetoothDevice.ActionFound.Equals(action))
            {
                BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                mDeviceList.Add(device.Name + ";" + device.Address);
                var path = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "Download";
                string filename = Path.Combine(path, "myfile.txt");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                using (StreamWriter objStreamWriter = new StreamWriter(filename, true))
                {
                    objStreamWriter.WriteLine(mDeviceList.Last());
                    objStreamWriter.Close();
                }
            }
        }
    }
}

这里,Activity类有一个BroadcastReceiver类,其中任何发现的蓝牙设备的MAC地址名称都被写入.txt文件。我是Xamarin的新手,也是Android的新手,以下是我感到困惑的事情:

  1. 我想知道如何获得包含所有蓝牙的列表 设备?
  2. 如何启动&#34;获取蓝牙设备&#34;事件?
  3. 我在代码中遗漏了什么?因为我什么都没发生 在我的Android智能手机中启动它。
  4. 我的主要目标是开始发现蓝牙设备但是如何?

1 个答案:

答案 0 :(得分:0)

好的,这很容易但是因为我是新手,所以需要一些时间来解决这个问题。我错过了SetContentView(Resources.Layout.Main)方法中的OnCreate,因此只需将OnCreate方法更改为:

 protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resources.Layout.Main); //add this line
    receiver = new DeviceDiscoveredReceiver(this);
    IntentFilter filter = new IntentFilter(BluetoothDevice.ActionFound);
    RegisterReceiver(receiver, filter);
    btAdapter = BluetoothAdapter.DefaultAdapter;
}