我正在尝试在Android.Xamarin中开发商店定位器应用。我的第一步是找到我所在位置的纬度和经度。
但是我的模拟器/设备屏幕什么也没显示。
我将uses-permissions
设置为<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
这是我的代码: -
Location _currentLocation;
LocationManager _locationManager;
TextView _locationText;
TextView _addressText;
string _locationProvider;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
_addressText = FindViewById<TextView>(Resource.Id.address_text);
_locationText = FindViewById<TextView>(Resource.Id.location_text);
FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick;
InitializeLocationManager();
}
void InitializeLocationManager()
{
_locationManager = (LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine
};
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
else
{
_locationProvider = String.Empty;
}
}
protected override void OnResume ()
{
base.OnResume ();
_locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
}
protected override void OnPause ()
{
base.OnPause ();
_locationManager.RemoveUpdates(this);
}
async void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
if (_currentLocation == null)
{
_addressText.Text = "Can't determine the current address.";
return;
}
Geocoder geocoder = new Geocoder(this);
IList<Address> addressList = await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);
Address address = addressList.FirstOrDefault();
if (address != null)
{
StringBuilder deviceAddress = new StringBuilder();
for (int i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceAddress.Append(address.GetAddressLine(i))
.AppendLine(",");
}
_addressText.Text = deviceAddress.ToString();
}
else
{
_addressText.Text = "Unable to determine the address.";
}
}
#region ILocationListener implementation
public void OnLocationChanged (Location location)
{
_currentLocation = location;
if (_currentLocation == null)
{
_locationText.Text = "Unable to determine your location.";
}
else
{
_locationText.Text = String.Format("{0},{1}", _currentLocation.Latitude, _currentLocation.Longitude);
}
}
public void OnProviderDisabled (string provider)
{
}
public void OnProviderEnabled (string provider)
{
}
public void OnStatusChanged (string provider, Availability status, Bundle extras)
{
}
#endregion
我得到如下输出: -
答案 0 :(得分:2)
如果您在模拟器中执行此代码,请记住,模拟器不显示GPS信息。当您在真实设备中尝试上述代码时,请确保您的GPS已开启,您应该在开阔天空或靠近窗口的地方。