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

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

class MainActivity: Activity { BluetoothAdapter btAdapter; static ArrayAdapter newDevicesArrayAdapter; public static List mDeviceList = new List(); 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. 如何启动“获取蓝牙设备”事件?
  3. 我在代码中遗漏了什么吗? 因为当我在我的Android智能手机中启动时没有任何反应。

我的主要目标是开始发现蓝牙设备,但是如何?

好吧,这很容易但是因为我是新手,所以需要一些时间来解决这个问题。 我错过了OnCreate方法中的SetContentView(Resources.Layout.Main) ,所以只需将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; }