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

nay*_*mtz 8 background-service xamarin foreground-service xamarin.forms

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

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

Mik*_*res 5

您可能想看看艾伦·里奇的《闪亮》。它目前处于测试阶段,但我仍然建议使用它,因为它可以为您自己编写此代码省去很多麻烦。这是Allan的一篇博客文章,解释了您可以在后台任务方面使用 Shiny 做什么 - 我认为计划作业是您正在寻找的东西。

  • 但这行不通吧?因为您需要前台服务才能经常获取位置。 (2认同)

Jac*_*Hua 5

我必须创建一个依赖服务,但我不知道如何。

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

public interface IStartService
{

    void StartForegroundServiceCompat();
}
Run Code Online (Sandbox Code Playgroud)

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

[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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦你想StartForegroundServiceCompatXamarin.forms项目中调用该方法,你可以使用:

public MainPage()
{
    InitializeComponent();

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

}
Run Code Online (Sandbox Code Playgroud)

这是关于依赖服务的文档

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

  • “主活动.实例”。我没有实例,它是空的。我怎样才能解决这个问题?:) (2认同)