繁体   English   中英

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

[英]How to open setting from our application in xamarin.forms?

我正在研究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));
        }
    }
}

但它给了我一个例外

{Android.Util.AndroidRuntimeException:从Activity上下文外部调用startActivity()需要FLAG_ACTIVITY_NEW_TASK标志。 这真的是你想要的吗? 在/ Users / ...中的System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()[0x0000c]

我该怎么办?

这是特定于平台的功能,因此您应该为它创建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,所以将注入每个平台的正确实现。 因此,不需要if (Device.OS == TargetPlatform.Android)行,除非您出于其他原因这样做。 此外,我认为此方法现已弃用 您现在应该使用Device.RuntimePlatform == Device.Android作为Xamarin.Forms 2.3.4。

在Android中,我使用它(使用DependencyServices调用)来打开“设置”

    public void View(){
        LocationManager locationManager = (LocationManager)Forms.Context.GetSystemService(Context.LocationService);

        if (locationManager.IsProviderEnabled(LocationManager.GpsProvider) == false)
        {
            Intent gpsSettingIntent = new Intent(Settings.ActionLocationSourceSettings);
            Forms.Context.StartActivity(gpsSettingIntent);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM