如何在Xamarin.Forms中创建永不结束的后台服务?

问题描述 投票:0回答:2

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

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

xamarin xamarin.forms background-service foreground-service
2个回答
2
投票

您可能想看看Allan Ritchie的Shiny。它仍处于beta中,但我仍建议使用它,因为它将省去编写此代码的麻烦。这是一个blog post by Alan,从后台任务的角度解释了可以使用Shiny进行的操作-我认为Scheduled Jobs是您想要的东西。


0
投票

我必须创建一个dependencyservice,但是我不知道如何。

首先,在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

        }
    }
}

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

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,如果用户在任务栏中关闭应用程序,则您将不再能够运行任何服务。如果应用程序正在运行,则可以阅读有关ios-backgrounding-walkthroughs/location-walkthrough

的文档
© www.soinside.com 2019 - 2024. All rights reserved.