如何使用 .Net Maui 检查系统蓝牙是否打开/关闭(平台 - Windows)?

Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 37,111 信誉分 Microsoft 供应商
2024-03-12T09:30:47.94+00:00

BLUETOOTH.cs

using Windows.Devices.Radios;
 
namespace ZolaApplication.Platforms.Windows
{
    public class Bluetooth : IBluetooth
    {
        public async Task<bool> GetBluetoothIsEnabledAsync()
        {
            var radios = await Radio.GetRadiosAsync();
            var bluetoothRadio = radios.FirstOrDefault(radio => radio.Kind == RadioKind.Bluetooth);
            return bluetoothRadio != null && bluetoothRadio.State == RadioState.On;
        }
    }
}

enter image description here IBLUETOOTH.cs

namespace ZolaApplication.Platforms.Windows
{
    public  interface IBluetooth
    {
        Task<bool> GetBluetoothIsEnabledAsync();
    }
}

如何在我所需的 ViewModel 中调用此功能? 此问题整理于[How to check system Bluetooth is On/Off (platform - Windows) using .Net Maui programming? - Microsoft Q&A](https://learn.microsoft.com/en-us/answers/questions/1314706/how-to-check-system-bluetooth-is-on-off-(platform )

.NET MAUI
.NET MAUI
一种 Microsoft 开源框架,用于构建跨移动设备、平板电脑、台式机的原生设备应用程序。
50 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 27,126 信誉分 Microsoft 供应商
    2024-03-12T09:35:36+00:00

    你好,

    您在 Windows 平台上实现了接口,但不知道如何在单个共享 MAUI 项目中调用该方法,对吗?如果是这样,您可以在 ViewModel 类中添加这个方法,并使用条件编译 来针对 Windows 平台。或者也可以直接调用平台代码。请参考以下代码:

    #if WINDOWS
    Using ZolaApplication.Platforms.Windows
    #endif
    public  class ViewModel{
        public async void iSEnableAsync()
        {
    #if WINDOWS
            // invoke the method you defined 
            //Bluetooth bluetooth = new Bluetooth();
            //   bool isEnable =    await bluetooth.GetBluetoothIsEnabledAsync();
     
    //invoke the platform code directly
           var accessLevel = await Radio.RequestAccessAsync();// request access
            if (accessLevel != RadioAccessStatus.Allowed)
            {
                Debug.WriteLine("Failed");
            }
            else
            {
                var radios = await Radio.GetRadiosAsync();
                var bluetoothRadio = radios.FirstOrDefault(radio => radio.Kind == RadioKind.Bluetooth);
                bool isEnable = bluetoothRadio != null && bluetoothRadio.State == RadioState.On;
                if (isEnable){...}
            }
    #endif
        }
    }
    

    之后您可以调用该方法

    private  void OnCounterClicked(object sender, EventArgs e)
        {
            var VM = this.BindingContext as ViewModel;
            VM.iSEnableAsync();
        }
    

    此外,请注意在 Package.appxmanifest 中添加:<DeviceCapability Name="radios"/>


    如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。 注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助