Xamarin 表单 -- 检测外部蓝牙'turn on'并在应用中相应地切换'switch'



有没有办法让应用程序从外部触发器读取蓝牙激活,例如,当用户向下滑动屏幕并打开它时,并在应用程序中相应地切换开关(即,如果用户从外部打开它,那么我的开关应该自动切换到打开状态,反之亦然(。这是我用来在应用程序中打开和关闭蓝牙的xamarin C#代码
主要活动.cs

void Enable(object sender, EventArgs e)
{
BluetoothManager _manager;
_manager = (BluetoothManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.BluetoothService);
bool on = _manager.Adapter.IsEnabled;
if (on == true)
{
string error = "Bluetooth is Already on";
Toast.MakeText(this, error, ToastLength.Long).Show();
e.Equals(true);
}
else
{
string okay = "Bluetooth has been turned on";
_manager.Adapter.Enable();
Toast.MakeText(this, okay, ToastLength.Long).Show();
}
}
void Disable(object sender, EventArgs e)
{
BluetoothManager _manager;
_manager = (BluetoothManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.BluetoothService);
bool on = _manager.Adapter.IsEnabled;
if (on == false)
{
string error = "Bluetooth is Already off";
Toast.MakeText(this, error, ToastLength.Long).Show();
e.Equals(false);

}
else
{
string okay = "Bluetooth has been turned off";
_manager.Adapter.Disable();
Toast.MakeText(this, okay, ToastLength.Long).Show();
}
}

我在主要活动中使用的订户消息中心是这个

BluetoothAndroid();
MessagingCenter.Subscribe<object, bool>(this, "Bluetooth", (sender, isEnabled) =>
{
if (isEnabled)
{
Enable(null, new EventArgs());
}
else
{
Disable(null, new EventArgs());
}
});

MainPage.xaml.cs Subscriber.sender方法为

private  void Enable(object sender, ToggledEventArgs e) {
if (e.Value == true)
{
MessagingCenter.Send<object, bool>(this, "Bluetooth", true);
// await DisplayAlert("Bluetooth Status", "Bluetooth has been turned on", "OK");
}
else
{
MessagingCenter.Send<object, bool>(this, "Bluetooth", false);
// await DisplayAlert("Bluetooth Status", "Bluetooth has been turned off", "OK");
}
}

我所需要的只是C sharp代码,以进入ART,导出状态,并在用户从外部活动触发状态时将开关的切换设置为打开或关闭,谢谢

您可以创建一个BroadcastReceiver侦听android.bluetooth.adapter.action.STATE_CHANGED操作并采取相应的行动。

[BroadcastReceiver]
[IntentFilter(new[] { BluetoothAdapter.ActionStateChanged })]
public class BluetoothStateChangedReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
if (intent.Extras == null)
return;
var state = intent.GetIntExtra(BluetoothAdapter.ExtraState, -1);
switch(state)
{
case (int)State.On:
// bluetooth is on
break;
case (int)State.Off:
// bluetooth is off
break;
}
}
}

你需要实例化并注册你的接收器,一个好地方就是你的MainActivity。

最新更新