簡體   English   中英

提示用戶啟用藍牙 Xamarin Forms

[英]Prompt User to enable bluetooth in Xamarin Forms

是否有任何解決方法可以用來提示用戶在 Xamarin Forms / 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 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();

此方法需要BLUETOOTHBLUETOOTH_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM