【发布时间】:2017-05-03 05:55:23
【问题描述】:
是否有任何解决方法可用于提示用户在 Xamarin Forms / C# 中启用蓝牙?
类似于带有“是”或“否”的显示警报,用于提示用户在蓝牙未启用时打开蓝牙。
如果用户选择“是”,则启用蓝牙。
请帮助我在 Android 和 iOS 中实现这一目标!提前致谢。
【问题讨论】:
标签: c# xamarin xamarin.ios xamarin.android
是否有任何解决方法可用于提示用户在 Xamarin Forms / C# 中启用蓝牙?
类似于带有“是”或“否”的显示警报,用于提示用户在蓝牙未启用时打开蓝牙。
如果用户选择“是”,则启用蓝牙。
请帮助我在 Android 和 iOS 中实现这一目标!提前致谢。
【问题讨论】:
标签: c# xamarin xamarin.ios xamarin.android
在 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 权限才能工作。
【讨论】:
State 属性在任何情况下是否始终 100% 正确。
root=Bluetooth,您将收到消息“您的应用使用“prefs:root=”非公共 URL 方案,这是一个私有实体。在 App Store 上不允许使用非公共 API,因为如果这些 API 发生变化,可能会导致糟糕的用户体验。”来自苹果。您只能使用UIApplication.SharedApplication.OpenUrl(new NSUrl("app-settings:"); 访问常规设置。
在 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
【讨论】: