[英]Prompt User to enable bluetooth in Xamarin Forms
是否有任何解决方法可以用来提示用户在 Xamarin Forms / C# 中启用蓝牙?
就像带有“是”或“否”的显示警报,提示用户在未启用蓝牙的情况下打开蓝牙。
如果用户选择“是”,则启用蓝牙。
请帮助我在 Android 和 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 Store 批准,因为“App-Prefs:root”也被视为具有此解释的私有 API:(感谢 @chucky 提到这一点)
您的应用程序使用“prefs:root=”非公共 URL 方案,这是一个私有实体。 App Store 不允许使用非公共 API,因为如果这些 API 发生变化,可能会导致糟糕的用户体验。
因此,对于 iOS,不可能没有应用程序被拒绝的风险。
Android.Bluetooth.BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
// is bluetooth enabled?
bluetoothAdapter.IsEnabled;
bluetoothAdapter.Disable();
// or
bluetoothAdapter.Enable();
此方法需要BLUETOOTH
和BLUETOOTH_ADMIN
权限才能工作。
在 Xamarin 表单中
if(await DisplayAlert(null,"Enable Bluetooth","Yes", "No"))
{
// Enablebluetooth here via custom service
}
对于蓝牙实现,请在 nugget 中下载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();
}
}
在安卓中
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
我不知道 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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.