[英]Bluetooth Radio.StateChanged Event fires twice
我想在藍牙收音機打開或關閉時收聽。 為此,我只是獲得了默認收音機並訂閱了 StateChanged。
var bluetoothAdapter = await BluetoothAdapter.GetDefaultAsync();
var radio = await bluetoothAdapter.GetRadioAsync();
radio.StateChanged += Radio_StateChanged;
private void Radio_StateChanged(Windows.Devices.Radios.Radio sender, object args)
{
Console.WriteLine(String.Format("Radio state changed {0} {1}", sender.Kind, sender.Name));
}
當我通過 Windows 藍牙設置更改藍牙 state 時,我得到了兩次 StateChanged 事件。
Output:
Radio state changed Bluetooth Bluetooth
Radio state changed Bluetooth Bluetooth
我將模塊與藍牙和 Wifi 放在一起。 我想也許這是原因。 然后我得到所有收音機Radio.GetRadiosAsync
radios = await Radio.GetRadiosAsync();
foreach (var r in radios)
{
r.StateChanged += Radio_StateChanged;
}
Output:
Radio state changed Bluetooth Bluetooth
Radio state changed Bluetooth Bluetooth
Radio state changed WiFi Wi-Fi
Radio state changed WiFi Wi-Fi
這是預期的行為嗎?
更新。 我將 state 值添加到 output
Output:
Radio state changed Bluetooth Bluetooth Off
Radio state changed Bluetooth Bluetooth Off
這可能是Radio.StateChanged API 的錯誤。 我也面臨同樣的問題。 您可以通過檢查無線電 State 來最小化問題,如下所示:
public Radio BluetoothAdapter { get; set; }
public RadioState OldBluetoothState;
public RadioState NewBluetoothState;
IReadOnlyList<Radio> radios = await Radio.GetRadiosAsync();
BluetoothAdapter = radios.FirstOrDefault(radio => radio.Kind == RadioKind.Bluetooth);
if (BluetoothAdapter != null)
{
OldBluetoothState = BluetoothAdapter.State;
BluetoothAdapter.StateChanged += RadioBluetoothAdapter_StateChanged;
}
private void RadioBluetoothAdapter_StateChanged(Radio sender, object args)
{
try
{
NewBluetoothState = sender.State;
if (NewBluetoothState != OldBluetoothState)
{
OldBluetoothState = NewBluetoothState;
if (sender.State == RadioState.Off)
{
//Application logic will goes here.
Debug.WriteLine("Bluetooth has been turned off.");
}
else
{
//Application logic will goes here.
Debug.WriteLine("Bluetooth has been turned on.");
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"Exception has been occured: {ex.Message.ToString()}");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.