Xamarin Forms-每10秒获取一次设备位置(当应用在前台/后台运行时) [英] Xamarin Forms - Get device location every 10 seconds (when app runs in foreground/background)

查看:386
本文介绍了Xamarin Forms-每10秒获取一次设备位置(当应用在前台/后台运行时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了Xamarin表单应用程序.该应用程序应定期(每10秒)获取设备(iOS和Android)的位置.我怎样才能做到这一点?我知道有一些库,例如:Xamarin.Essentials,但是我无法确定应该使用该位置多少次.

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.

当Xamarin表单应用程序在后台(在IOS和Android上)运行时,也应该有可能获取设备的本地信息.

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

推荐答案

对于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

这篇关于Xamarin Forms-每10秒获取一次设备位置(当应用在前台/后台运行时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆