Forum Xamarin.Android

Calculate GPS position every second in the background?

Started programming in Android and i seem to have problems with having something running continuously in the background.
This is the code that i have in MainActivity

async Task task()
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
var speed = position.Speed * 3.6;
speedKmh = speed.ToString() + "km/h";
i want it to start at the beginning of the application and basically run it every 1 second so i can display the device's speed using GPS.It must be really simple but i just don't know how.
Many thanks!


  • RyanFrenchRyanFrench USMember ✭✭
    edited July 2017

    You need to use a Service, what your trying to do is not appropriate in main.
    Ditch CrossGeolocator and take a look at the attached code files.

    Next from main use the below line to start the service.

    ApplicationContext.StartService(new Intent(ApplicationContext, typeof(LocationLoggingService)));

    Within the LocationManager set the interval (in ms) of how often you would like the system to calculate the location. Currently it is set at every 20 minutes.

  • RyanFrenchRyanFrench USMember ✭✭
    edited July 2017

    Note that the location object contains the speed property that you are after.
    Also note that with Android O, there are some new limitations for obtaining the location in the background. I believe the solution would be to run the service in foreground.

  • abhishekgoutamabhishekgoutam USMember ✭✭

    @RyanFrench How can i use the code if i am using PCL. Can you please provide me the sample. I am trying to implement this in Android / IOS both platform.


Sign In or Register to comment.