【发布时间】:2020-11-21 07:42:50
【问题描述】:
每当我打开我的应用程序时,我都需要检查 GPS 是打开还是关闭。如果 GPS 关闭,我需要将用户重定向到位置设置页面。我已经使用dependency service 完成了android 部分,如下所示。
ILocSettings
public interface ILocSettings
{
void OpenSettings();
bool isGpsAvailable();
}
Android 实现
[assembly: Dependency(typeof(LocationShare))]
namespace Projectname.Droid.Services
{
public class LocationShare : ILocSettings
{
public bool isGpsAvailable()
{
bool value = false;
Android.Locations.LocationManager manager = (Android.Locations.LocationManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.LocationService);
if (!manager.IsProviderEnabled(Android.Locations.LocationManager.GpsProvider))
{
//gps disable
value = false;
}
else
{
//Gps enable
value = true;
}
return value;
}
public void OpenSettings()
{
Intent intent = new Android.Content.Intent(Android.Provider.Settings.ActionLocationSourceSettings);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
}
最后来自共享项目,如下所示:
//For checking the GPS Status
bool gpsStatus = DependencyService.Get<ILocSettings>().isGpsAvailable();
//For opening the location settings
DependencyService.Get<ILocSettings>().OpenSettings();
对于 ios,我怎样才能实现相同的功能?我尝试如下:
[assembly: Dependency(typeof(LocationShare))]
namespace Projectname.iOS.Serivces
{
class LocationShare : ILocSettings
{
public bool isGpsAvailable()
{
//how to check the GPS is on or off here
}
public void OpenSettings()
{
UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));
}
}
}
在ios模拟器上打开位置设置页面,但不知道如何查看GPS状态。
更新1
我已经尝试了CLLocationManager 代码,但它没有按预期工作。即使 location 关闭或打开,它也始终返回 true。
OpenSettings() 功能代码 (UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString));) 也没有按预期工作,它正在重定向到其他一些 page,如果 GPS 关闭,我需要打开位置 settings page。
另外,我正在请求位置权限,如下所示:
var status = await Permissions.RequestAsync<Permissions.LocationAlways>();
在android 中,请求位置权限,但在 ios 中,没有请求权限。
更新2
我已经尝试了新代码并始终获得错误值作为 GPS 状态。我已经在info.plist 上添加了所有位置权限,如下所示:
但是在运行应用程序时不会询问位置权限(甚至一次都没有)。我试过Permissions.LocationWhenInUse而不是Permissions.LocationAlways,但没有运气。
更新 3
以下是我检查位置权限、检查 GPS 状态和打开设置的完整流程。权限状态值始终为Disabled。
//Requesting permission like below:
var status = await Permissions.RequestAsync<Permissions.LocationAlways>();
if (status == PermissionStatus.Granted)
{
//Then checking the GPS state like below
bool gpsStatus = DependencyService.Get<ILocSettings>().isGpsAvailable();
if (!gpsStatus)
{
//show a message to user here for sharing the GPS
//If user granted GPS Sharing, opening the location settings page like below:
DependencyService.Get<ILocSettings>().OpenSettings();
}
}
我已尝试使用以下 2 个代码来请求或检查权限。在这两种情况下,状态值都是禁用的。如果我卸载该应用程序并重新安装它,获得相同的状态并且没有显示任何权限弹出窗口。
var status = await Permissions.RequestAsync<Permissions.LocationAlways>();
var status = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
【问题讨论】:
-
使用 Essentials 并检查 FeatureNotEnabledException
标签: ios xamarin.forms gps