且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Xamarin Forms-每10秒获取一次设备位置(当应用在前台/后台运行时)

更新时间:2022-12-27 11:22:32

对于Android,您可以尝试启动一个服务,该服务使用Android的LocationManager来开始侦听位置更改.您可以指定时间间隔和要跟踪的最小距离.

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).

要获取位置,我将Service设置为"LocationListener",并实现了ILocationListener-Interface,如下所示:

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.

要注意的重要是,locationUpdates的时间不固定(有时花费了10秒钟以上),因为您只给出了MinimumTime,并且OS根据请求的容量对其进行处理.但这还不错.

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.

更新:这似乎不适用于Android 8.0及更高版本.请参见此处

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