.NET MAUI开放系统设置

问题描述 投票:0回答:2

有人可以告诉我如何使用.NET MAUI 强制系统打开系统设置,或者更好的系统设置 > myApp > 权限?我正在尝试编写代码,在不允许应用程序使用相机后将用户重定向到设置。

Android 和 iOS

我尝试寻找与意图相关的东西

.net maui
2个回答
13
投票

在以前称为 Essentials 的 API 中,有

AppInfo
,可让您打开应用程序的设置页面。

您可以将其用作

AppInfo.Current.ShowSettingsUI();

在文档中了解更多相关信息:https://learn.microsoft.com/dotnet/maui/platform-integration/appmodel/app-information?view=net-maui-7.0&tabs=ios#display-app-settings


0
投票

例如,要导航到“设备位置设置”,您必须执行以下操作。对于其他设置,您只需更改设备特定代码中的位置即可。注意评论

在你的基础项目中

public interface ILocationSettingsService
{
    void OpenSettings();
}

然后在Android中新建一个类LocationSettingsService

并添加

[assembly:Microsoft.Maui.Controls.Dependency(typeof(LocationSettingsService))] 

使用后。

public class LocationSettingsService : ILocationSettingsService
{
    public void OpenSettings()
    {
        Intent intent = new(Settings.ActionLocationSourceSettings); //Settings.[Your location in settings]
        intent.AddCategory(Intent.CategoryDefault);
        intent.SetFlags(ActivityFlags.NewTask);
        Platform.CurrentActivity.StartActivityForResult(intent, 0);

    }
}

在 iOS 中类似,添加

[assembly:Microsoft.Maui.Controls.Dependency(typeof(LocationSettingsService))]

使用后,上面的命名空间

public class LocationSettingsService : ILocationSettingsService
{
    public void OpenSettings()
    {
        var url = new NSUrl("app-settings:"); //app-settings: your url
        if (UIApplication.SharedApplication.CanOpenUrl(url))
        {
            UIApplication.SharedApplication.OpenUrl(url);
        }
    }
}

然后在MauiProgram.cs中 使用条件编译注册特定于平台的服务

#if ANDROID
            builder.Services.AddTransient<ILocationSettingsService, Platforms.Android.LocationSettingsService>();
#elif IOS
            builder.Services.AddTransient<ILocationSettingsService, Platforms.iOS.LocationSettingsService>();
#endif

最后,


_locationSettingsService = IPlatformApplication.Current.Services?.GetService<ILocationSettingsService>() 
            ?? throw new InvalidOperationException("LocationSettingsService is not available.");

_locationSettingsService?.OpenSettings();

注意 请务必替换“设置”。[您在设置中的位置]和应用程序设置:将您的 URL 替换为设置中的实际位置和应用程序的 URL。

© www.soinside.com 2019 - 2024. All rights reserved.