My application gives an error:
The current Activity can not be detected. Ensure that you have called Init in your Activity or Application class.
I use the emulator Genymotion. GPS enabled
public async Task btnAdd_Click()
{
try
{
var request = new GeolocationRequest(GeolocationAccuracy.Medium);
var location = await Geolocation.GetLocationAsync(request);
if (location != null)
{
string note = "GPS: Latitude-" + location.Latitude + " Longitude-" + location.Longitude;
}
}
catch (Exception ex)
{
// Unable to get location
}
}
Improve Gerald answer by offer full code
protected async override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
txtnumber = FindViewById<TextView>(Resource.Id.textView1);
txtnumber.Text ="Initializing";
try
{
var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
var location = await Geolocation.GetLocationAsync(request);
txtnumber.Text = "finish read geolocation";
if (location != null)
{
txtnumber.Text = "GPS: Latitude-" + location.Latitude + " Longitude-" + location.Longitude;
}
}
catch (FeatureNotSupportedException fnsEx)
{
// Handle not supported on device exception
}
catch (FeatureNotEnabledException fneEx)
{
// Handle not enabled on device exception
}
catch (PermissionException pEx)
{
// Handle permission exception
}
catch (Exception ex)
{
// Unable to get location
txtnumber.Text = ex.Message.ToString();
}
}
Like the error states, did you add this line:
Xamarin.Essentials.Platform.Init(this, bundle);
In your MainActivity.cs
in the OnCreate
method?
First you need init Xamarin Essentials in OnCreate function from MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
...
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
...
}
Then overide the function should work
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With