在多个论坛和网站讲述如何发现蓝牙设备(配对或未配对)之后,我写下了这段代码。
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的新手,以下是我感到困惑的事情:
我的主要目标是开始发现蓝牙设备但是如何?
答案 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;
}