【问题标题】:How to create a never ending background service in Xamarin.Forms?如何在 Xamarin.Forms 中创建永无止境的后台服务?
【发布时间】:2020-01-26 04:26:10
【问题描述】:

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

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

【问题讨论】:

  • 对于 Android 我可以说它永远无法保证后台服务将始终运行,因为一些限制,例如当设备的资源处于压力之下时,谷歌也在较新的 Android 版本中施加了进一步的限制,甚至一些制造商的限制。 Android 的一种可能选择是使用Foreground Services
  • 谢谢你,这个信息对我很重要

标签: xamarin xamarin.forms background-service foreground-service


【解决方案1】:

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

首先,在 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,如果用户在任务栏中关闭应用程序,您将无法再运行任何服务。如果应用正在运行,你可以阅读这篇关于ios-backgrounding-walkthroughs/location-walkthrough的文档

【讨论】:

  • “MainActivity.Instance”。我没有实例,它是空的。我怎样才能解决这个问题? :)
  • 在您的 MainActivity 中创建一个静态 Instance 属性。
  • 你好。我无法找到这个“实例”。这是什么?
  • 是MainActivity的引用。
  • 你好。你能帮我定义 IBinder 吗?
【解决方案2】:

您可能想看看 Allan Ritchie 的 Shiny。它目前处于测试阶段,但我仍然建议使用它,因为它会为您自己编写此代码省去很多麻烦。这是blog post by Allan,解释了您可以在后台任务方面使用 Shiny 做什么 - 我认为 Scheduled Jobs 是您正在寻找的东西。

【讨论】:

  • 但这行不通?因为您需要前台服务才能经常获取位置..
猜你喜欢
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多