1
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Locations;
using Android.Content;
[Activity(Label = "Getlocation", MainLauncher = true)]
public class MainActivity : Activity, ILocationListener
{
Button bttnGo;
TextView txtLoc;
LocationManager locMgr;
Location currentLocation;
string provider;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
bttnGo = FindViewById<Button>(Resource.Id.get_address_button);
txtLoc = FindViewById<TextView>(Resource.Id.location_text);
InitializeLocationManager();
bttnGo.Click += BttnGo_Click;
}
async void BttnGo_Click(object sender, EventArgs e)
{
if (currentLocation == null)
{
txtLoc.Text = "No location found, try moving around";
}
else
{
txtLoc.Text = currentLocation.ToString();
}
}
private void InitializeLocationManager()
{
locMgr = (LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Fine
};
IList<string> acceptableLocationProviders = locMgr.GetProviders(criteriaForLocationService, true);
if(acceptableLocationProviders.Any())
{
provider = acceptableLocationProviders.First();
}
else
{
provider = string.Empty;
}
}
protected override void OnResume()
{
base.OnResume();
locMgr.RequestLocationUpdates(provider, 2000, 0, this);
}
protected override void OnPause()
{
base.OnPause();
locMgr.RemoveUpdates(this);
}
public void OnLocationChanged(Location location)
{
currentLocation = location;
if (currentLocation == null)
{
txtLoc.Text = "No location detected";
}
else
{
txtLoc.Text = location.Latitude.ToString();
}
}
public void OnProviderDisabled(string provider)
{
}
public void OnProviderEnabled(string provider)
{
}
public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
{
}
}
}
我的編碼知識很少,我只是按照教程來檢索當前位置。Xamarin android在位置更改前獲取位置
我的問題是,我只能檢索實際位置更改時的位置。我知道這可能是因爲currentLocation在OnLocationChanged發生之前沒有獲得值。如何去解決這個問題?