Reputation: 874
I am new to Android and Xamarin world. I am trying to create a separate class for Location Manager to be used in different activities. Here is my code
using System;
using Android.Content;
using Android.Locations;
namespace MyLocation
{
public class LocationManagerActivity
{
private LocationManager _locationManager;
private Geocoder _geocoder;
string bestProvider;
private Context locationContext;
public LocationManagerActivity (Context lContext)
{
locationContext = lContext;
}
private void getCurrentLocation()
{
string provider = LocationManager.GpsProvider;
if (_locationManager.IsProviderEnabled (provider)) {
_locationManager.RequestLocationUpdates (1000, 100, null, locationContext);
}
}
private void InitializeLocationManager()
{
_geocoder = new Geocoder (locationContext);
_locationManager = (LocationManager)locationContext.GetSystemService(Context.LocationService);
var criteria = new Criteria() { Accuracy = Accuracy.NoRequirement };
bestProvider = _locationManager.GetBestProvider(criteria, true);
Location lastKnownLocation = _locationManager.GetLastKnownLocation(bestProvider);
if (lastKnownLocation != null)
{
string temp = string.Format("Last known location lat: {0}, long: {1}",
lastKnownLocation.Latitude, lastKnownLocation.Longitude);
//string tag = "Last known location: ";
//Log.Info (tag, temp);
}
_locationManager.RequestLocationUpdates(bestProvider, 60000, 20, this);
}
}
}
The problem is in the line
locationManager.RequestLocationUpdates (1000, 100, null, locationContext);
Argument 4 has to be Android.App.PendingIntent. How do i set it as the class is not an activity.
Upvotes: 1
Views: 1069
Reputation: 4602
There is an overload of RequestLocationUpdates
that takes in a LocationListener
. See The docs.
So you can have your class implement ILocationListener
in Xamarin and implement the required methods such as onLocationChanged
etc. If you're not doing this in an Activity (or something that inherits from Java.Lang.Object
) you should have your class inherit from Java.Lang.Object
as it handles the Handle/Disposing for you.
public class LocationManagerActivity : Java.Lang.Object, ILocationListener
Then you can do this
_locationManager.RequestLocationUpdates(bestProvider, 60000, 20, this);
Upvotes: 2