提示用户以Xamarin表单启用蓝牙



是否有任何解决方法可以提示用户以xamarin表单启用蓝牙/c#?

喜欢带有"是"或"否"的显示警报,以提示用户未启用蓝牙。

如果用户选择"是",则启用了蓝牙。

请帮助我在Android和iOS中实现这一目标!预先感谢。

ios

在iOS上,如果不使用私有API(Apple不允许在App Store中(,您无法通过此代码将用户重定向到蓝牙设置(请注意,它仅适用于蓝牙设置真实设备(:

// Is bluetooth enabled?
var bluetoothManager = new CoreBluetooth.CBCentralManager();
if (bluetoothManager.State == CBCentralManagerState.PoweredOff) {
    // Does not go directly to bluetooth on every OS version though, but opens the Settings on most
    UIApplication.SharedApplication.OpenUrl(new NSUrl("App-Prefs:root=Bluetooth")); 
}

请注意,此方法将阻止您的应用程序获得应用商店的批准,因为" App-Prefs:root"也被视为具有此解释的私有API:(感谢@chucky提到那(

您的应用程序使用" prefs:root ="非公共URL方案,该方案是一个私人实体。App Store在App Store上不允许使用非公共API,因为如果这些API发生变化,它可能会导致用户体验差。

因此,对于iOS,如果没有应用拒绝的风险,就不可能。

Android

Android.Bluetooth.BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
// is bluetooth enabled?
bluetoothAdapter.IsEnabled;
bluetoothAdapter.Disable();
// or
bluetoothAdapter.Enable();

此方法工作需要BLUETOOTHBLUETOOTH_ADMIN许可。

我不知道ios,

如果您正在单击按钮,请从应用程序中从应用程序中导航到Android中的蓝牙设置。这是代码:

    private void OpenBluetoothSettings()
    {
        Intent intentOpenBluetoothSettings = new Intent();
        intentOpenBluetoothSettings.SetAction(Android.Provider.Settings.ActionBluetoothSettings);
        intentOpenBluetoothSettings.AddFlags(ActivityFlags.NewTask);
        Android.App.Application.Context.StartActivity(intentOpenBluetoothSettings);
    }

在xamarin表单中

if(await DisplayAlert(null,"Enable Bluetooth","Yes", "No"))
{
    // Enablebluetooth here via custom service
}

用于蓝牙实现下载Xamarin.bluetoothle中的块或您可以实现自己的

在pcl

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test.App
{
    public interface IBluetoothService
    {
        void OpenBluetooth();
        
    }
}

在Android

using System;
using BluetoothLE.Core;
using Android.Bluetooth;
using Java.Util;
using System.Collections.Generic;
using BluetoothLE.Core.Events;
namespace Test.App.Droid.Services
{
    public class BluetoothService : IBluetoothService
    {
    
        public void OpenBluetooth()
        {
        //native code here to open bluetooth
        }
    
    }
    
}
// register it on MainActivity

// do the same in ios

最新更新