Xamarin Forms - Get device location every 10 seconds (when app runs in foreground/background)

ⅰ亾dé卋堺 提交于 2020-04-07 09:27:23

问题


I have created a xamarin forms application. The application should periodically (every 10 sec) get the location of the device (IOS and Android). How can I achieve this? I know there are some libraries for example: Xamarin.Essentials, but I can't decide how many times the location should be taken.

It should also be possible to get the local of the device when the xamarin forms application runs in the background (on IOS and Android).

Hope someone can help me out with this one.


回答1:


For Android you can try to start a Service that uses the LocationManager of Android to start listening to Location changes. You can specify a timeinterval and a minimum distance you want to track.

This section helped me fiqure out how to use it. For me it was sending location updates even when the app was suspended (physical device running Android 6.1).

To get the location I made my Service a 'LocationListener' and implemented the ILocationListener-Interface like so:

[Service]
public class TestService : Service, ILocationListener
{
    public override IBinder OnBind(Intent intent)
    {
        return null;
    }


    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        // start your location updates with the locationManager here

        return StartCommandResult.Sticky; // remember to return sticky for the service to run when app is suspended
    }


    public override void OnDestroy() { }

    ...

    public void OnLocationChanged(Location location)
    {
        // react to location changes here
    }

    public void OnProviderDisabled(string provider) { }

    public void OnProviderEnabled(string provider) { }

    public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
}

For more information on Backgrounding and how to set up a service read this.

Important to note is that the locationUpdates where not consistantly timed (sometimes took more that 10 seconds), since you just give a minimumTime and the OS processes the Request based on its' capacities. But it wasn't too bad.

Update: this doesnt seem to work for Android 8.0 and above. see here



来源:https://stackoverflow.com/questions/60637197/xamarin-forms-get-device-location-every-10-seconds-when-app-runs-in-foregroun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!