gpt4 book ai didi

android - 如何从我们在 xamarin.forms 中的应用程序打开设置?

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:47 29 4
gpt4 key购买 nike

我正在研究 xamarin.forms。(仅在 android 中面临以下问题)

当我的应用程序启动时,它会检查我的 GPS 位置是打开还是关闭。

要检查 GPS 位置的开启或关闭,我正在使用依赖服务。

public static bool CheckGPSConnection()
{
var gpsConnection = DependencyService.Get<IGPSConnectivity>();
return gpsConnection.CheckGPSConnection();
}

当我来到我的应用程序主页时,我输入了以下代码

if (Device.OS == TargetPlatform.Android)
{
if (!App.CheckGPSConnection())
{
bool answer = await DisplayAlert("Alert", "Would you like to start GPS?", "Yes", "No");
if (answer)
{
Android.App.Application.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings));
}
}
}

但它给了我一个异常(exception)

{Android.Util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/…}

我该怎么办?

最佳答案

这是特定于平台的功能,因此您应该为它创建一个 DependencyService。

就像 IGPSConnectivity创建另一个界面。例如ISettingsService .

public interface ISettingsService
{
void OpenSettings();
}

然后在Android上,这样实现:

public class SettingsServiceAndroid : ISettingsService
{
public void OpenSettings()
{
Xamarin.Forms.Forms.Context.StartActivity(new Android.Content.Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings));
}
}

现在再次从您的共享 PCL 代码中调用它,就像使用 GPS 连接一样。

DependencyService.Get<ISettingsService>().OpenSettings();

因为您使用的是 DependencyService,所以将注入(inject)每个平台的正确实现。所以,不需要 if (Device.OS == TargetPlatform.Android)行,除非你这样做当然是出于其他原因。另外,我认为这种方法现在是 deprecated .您现在应该使用 Device.RuntimePlatform == Device.Android从 Xamarin.Forms 2.3.4 开始。

关于android - 如何从我们在 xamarin.forms 中的应用程序打开设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43608067/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com