如何检查 Xamarin Forms 中的定位服务是否“开启”?

Dhu*_*ayn 5 c# service location xamarin xamarin.forms

我的应用程序适用于位置。所以我需要打开定位服务。我看到有关在iOS平台上检查位置服务状态的问题,但是有没有办法在共享项目中检查这一点?

我正在寻找一种事件类型解决方案,如果用户关闭位置服务,应用程序将停止正在执行的操作并要求用户再次打开位置。

Wen*_* Li 5

您可以使用DependencyService查看该位置是否已打开。

这是我的cs代码:

private void Button_Clicked(object sender, EventArgs e)
{
    var check = DependencyService.Get<IDeviceOrientationService>().IsLocationServiceEnabled();
    if (check)
    {
        res.Text = "It is on";
    }
    else
    {
        res.Text = "It is off";
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的方法的实现代码(在 App.Android 中):

[assembly: Dependency(typeof(DeviceOrientationService))]
namespace App13.Droid
{
    class DeviceOrientationService : IDeviceOrientationService
    {
        public bool IsLocationServiceEnabled()
        {
           LocationManager locationManager = (LocationManager)Android.App.Application.Context.GetSystemService(Context.LocationService);
           return locationManager.IsProviderEnabled(LocationManager.GpsProvider);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是屏幕截图:

在此输入图像描述

  • 在你给我希望的地方,所有人都投了反对票,让我失去动力。 (2认同)
  • 祝你成功 (2认同)