如何在 Xamarin.Forms 中创建永无止境的后台服务?

How to create a never ending background service in Xamarin.Forms?

我每 15 分钟监控一次用户的位置,我只希望应用程序继续发送位置信息,即使用户在任务栏中关闭了应用程序。

我试过这个示例,但它在 Xamarin.Android https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/services/foreground-services 我必须创建一个依赖服务,但我不知道如何。

您可能想看看 Shiny by Allan Ritchie. It's currently in beta but I would still suggest using it, as it will save you a lot of trouble writing this code yourself. Here's a blog post by Allan,解释您可以在后台任务方面使用 Shiny 做什么 - 我认为 Scheduled Jobs 是您想要的东西正在寻找。

i have to create a dependencyservice but i don't know how.

首先,在Xamarin.forms项目中创建一个Interface

public interface IStartService
{

    void StartForegroundServiceCompat();
}

然后在xxx.Android项目中创建一个新文件让我们称之为itstartServiceAndroid来实现你想要的服务:

[assembly: Dependency(typeof(startServiceAndroid))]
namespace DependencyServiceDemos.Droid
{
    public class startServiceAndroid : IStartService
    {
        public void StartForegroundServiceCompat()
        {
            var intent = new Intent(MainActivity.Instance, typeof(myLocationService));


            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
            {
                MainActivity.Instance.StartForegroundService(intent);
            }
            else
            {
                MainActivity.Instance.StartService(intent);
            }

        }
    }

    [Service]
    public class myLocationService : Service
    {
        public override IBinder OnBind(Intent intent)
        {
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            // Code not directly related to publishing the notification has been omitted for clarity.
            // Normally, this method would hold the code to be run when the service is started.

            //Write want you want to do here

        }
    }
}

一旦要在Xamarin.forms项目中调用StartForegroundServiceCompat方法,可以使用:

public MainPage()
{
    InitializeComponent();

    //call method to start service, you can put this line everywhere you want to get start
    DependencyService.Get<IStartService>().StartForegroundServiceCompat();

}

这是关于 dependency-service

的文档

对于iOS,如果用户关闭任务栏中的应用程序,您将无法再运行任何服务。如果应用是 运行ning,您可以阅读这篇关于 ios-backgrounding-walkthroughs/location-walkthrough

的文档