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が場所を取得する
私の問題は、実際の場所が変更されたときにしか場所を取得できないことです。これはおそらく、OnLocationChangedが発生するまでcurrentLocationが値を取得していないためです。これを回避するには?