我想获取设备的GPS位置。我正在为Xamarin使用 GeolocatorPlugin 来获取设备的经度和纬度。我的设备上启用了GPS。我已经向我的Android清单添加了权限,但仍然收到错误:“发生地理位置错误:未经授权” 。如何解决此问题?
try
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync();
entLocation.Text = position.Longitude.ToString() + "," + position.Latitude.ToString();
}
catch (Exception ex)
{
//will catch any general exception and set message in a string
string msg = ex.Message;
await DisplayAlert("error", msg, "ok");
}
答案 0 :(得分:4)
将以下代码放入Android项目中的MainActivity.cs中。
if(CheckSelfPermission(Manifest.Permission.AccessCoarseLocation) != (int)Permission.Granted)
{
RequestPermissions(new string[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation }, 0);
}