Bluetoothアプリケーションを作成するには、コードのAndroid側でいくつかのブロードキャストアクションにアクセスする必要があります。
これはすべて私のコアで実行されるので、インターフェイスを介して呼び出すViewModelがあります
public interface IConnectionService
{
//Properties
string IntentName { get; }
//Events
event EventHandler<SearchConnectionItemEventArgs> SearchItemFoundEvent;
//Methods
void RunIntent();
void SearchConnection();
void Connect(string macAddress);
}
RunIntentは、Bluetoothをオンにするようにユーザーに促します(別のテクノロジーである可能性があります)。次に、Bluetoothの状態が変更されたときにイベントトリガーが必要です。
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
}
}