制作我的蓝牙应用程序时,我需要在我的代码的 Android 端访问一些广播操作。
所有这些都在我的核心中运行,所以我有一个 ViewModel 将通过我的界面调用
public interface IConnectionService
{
//Properties
string IntentName { get; }
//Events
event EventHandler<SearchConnectionItemEventArgs> SearchItemFoundEvent;
//Methods
void RunIntent();
void SearchConnection();
void Connect(string macAddress);
}
RunIntent 提示用户打开蓝牙(可能是另一种技术),然后我想在蓝牙状态改变时触发事件
Android.Bluetooth.BluetoothAdapter.ActionStateChanged
而且当我搜索我需要的新设备时
Android.Bluetooth.BluetoothDevice.ActionFound
但是我不能将 [Android.Runtime.Register("ACTION_FOUND")] 和 [Android.Runtime.Register("ACTION_STATE_CHANGED")] 放在我的课堂上,这只有在我尝试将它放在我的视图上时才有效,但是如果我我认为我需要逻辑吗?
是否有可能以某种方式将其放入核心?
我的类实现我的接口
using System;
using Android.Bluetooth;
using Android.Content;
using Cirrious.MvvmCross.Android.Platform.Tasks;
using Test.Core.Interfaces;
using Test.Core.Models;
namespace Test.Core.Android
{
public class AndroidBluetooth : MvxAndroidTask, IConnectionService
{
#region Private Fields
private readonly BluetoothAdapter _bluetoothAdapter;
#endregion
#region Public Fields
#endregion
#region Properties
public string IntentName { get { return "Turn on Bluetooth"; }}
#endregion
#region Constructor
public AndroidBluetooth()
{
_bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
}
#endregion
#region Events
public event EventHandler<SearchConnectionItemEventArgs> SearchItemFoundEvent;
private void ItemFound(SearchConnectionItemEventArgs e)
{
if(SearchItemFoundEvent != null)
{
SearchItemFoundEvent(this, e);
}
}
#endregion
#region Methods
public void RunIntent()
{
if (_bluetoothAdapter == null)
{
//No bluetooth support on phone
}
else if(!_bluetoothAdapter.IsEnabled)
{
var intent = new Intent(BluetoothAdapter.ActionRequestEnable);
StartActivity(intent);
}
}
public void SearchConnection()
{
if (_bluetoothAdapter == null)
{
//No bluetooth support on phone
}
else if (!_bluetoothAdapter.IsEnabled)
{
//Bluetooth not turned on
RunIntent();
}
else
{
FindBondedDevices();
}
}
private void FindBondedDevices()
{
var pairedDevices = _bluetoothAdapter.BondedDevices;
if (pairedDevices.Count <= 0) return;
foreach (var item in pairedDevices)
{
ItemFound(new SearchConnectionItemEventArgs {Name = item.Name, MacAddress = item.Address});
}
}
private void FindNewDevices()
{
if (_bluetoothAdapter == null)
{
}
else if (!_bluetoothAdapter.IsEnabled)
{
}
else
{
_bluetoothAdapter.StartDiscovery();
//Bind event for new devices
}
}
public void Connect(string macAddress)
{
}
#endregion
}
}