如何在Xamarin.Forms应用程序中打开设置?

4

我正在开发xamarin.forms应用。(仅在安卓平台上出现以下问题)

当我的应用程序启动时,它会检查我的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标志。这真的是你想要的吗?在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() [0x0000c]中 [Users/…}

我该怎么办?


1
如果您正在使用Forms,那么您可能想要使用Xamarin.Forms.Forms.Context - Gerald Versluis
var intent = new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);变量意图=新的Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings); 意图.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - Dilmah
很奇怪,它应该在那里。这段代码是在哪个项目中?是Droid项目吗?还是你正在使用共享项目而不是PCL? - Gerald Versluis
我正在使用Xamarin.Forms而不是原生开发,在PCL上工作。 - RMR
是的,在Dorid项目中我找到了它,但在PCL中没有。所以要在PCL中访问它,我必须使用Dependency Service,对吗? - RMR
显示剩余4条评论
2个回答

11

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

就像为IGPSConnectivity创建另一个接口一样。例如ISettingsService

public interface ISettingsService
{
    void OpenSettings();
}

那么在安卓上,可以这样实现:

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)行。另外,我认为此方法现在已废弃。自Xamarin.Forms 2.3.4起,您应该使用Device.RuntimePlatform == Device.Android


1
如果您遇到命名空间问题,请使用“global::”前缀:global::Android.Content.Intent - Benni

0
在安卓中,我使用这个(使用 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);
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接