专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

如何在Xamarin.Forms中创建永无止境的后台服务?(How to create a never ending background servi

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 0:57:24       共计:3601 浏览

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

我尝试了此示例,但它在Xamarin.Android中 https://docs.microsoft.com/zh-cn/xamarin/android/app-fundamentals/services/foreground-services 我必须创建一个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

        }
    }
}

一旦要在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();

}

以下是有关依赖关系的文档服务

对于iOS,如果用户在任务栏中关闭应用程序,则您将不再能够运行任何服务.如果应用程序正在运行,则可以阅读有关 ios-backgrounding-walkthroughs/location-walkthrough

版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:利用雷电模拟器打造一个安卓电视盒子 | ·下一条:Android平台-极光服务 SDK 一键接入指南

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有