如何在Xamarin.Forms

时间:2018-03-22 00:38:57

标签: android xamarin service xamarin.forms android-service

我尝试定期检查Web服务是否已将新项目添加到数据库中。如果有新项目,则应更新用户看到的列表视图。 我正在使用PCL,我已经完成了创建一个带有计时器的新任务。但这仅在应用程序打开时有效。我想在关闭应用程序时执行相同操作,以便用户在远程添加新项目时收到通知。 我一直在做一些研究,我找到了andoid服务,信息说服务将继续,无论应用程序状态如何,直到你告诉它停止。但我还没有找到很多关于如何实施它的例子。

这里的代码只有在应用程序打开时才有效:

 Task.Run(() =>
            {
                Device.StartTimer(TimeSpan.FromSeconds(secs), checkUpdates);
            });

  bool checkUpdates()
      {
        if (isOnline)
        {
            var lastUp= Application.Current.Properties["lastUpdate"] as string;

    //returns true if a new item is added
            if (service.newItem(DateTime.Parse(lastUp)))
            {
                var itm = service.getNewItem(DateTime.Parse(lastUp));

                Device.BeginInvokeOnMainThread(() =>
                {
                        notification.ShowNotification(itm.Title, 1000);
                        listView.Insert(0, itm);
                 }                        
                });                  
            }
            App.Current.Properties["lastUpdate"] = DateTime.Now.ToString();
        }
        return true;
    }

我尝试使用依赖服务对Android服务做同样的事情,这是我到目前为止所做的:

 public interface IService
    {
        void Start();
    }

  [Service]
    public class DependentService : Service, IService
    {
        public void Start()
        {
            var intent = new Intent(Android.App.Application.Context, typeof(DependentService));
            Android.App.Application.Context.StartService(intent);
        }

        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            // From shared code or in your PCL


            return StartCommandResult.NotSticky;
        }
    }

问题是我不知道如何在计时器中实现我的服务代码,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

对于您想要实现的目标,您应该查看AlarmManager

看看这个StackOverflow post,其中有一个例子,也可能是this one。第二个是Java,但它可能会让你知道你可能会处理什么

编辑:

您可能还想查看围绕ServicesBroadcastReceivers的这些Xamarin.Android文档,以便更好地了解您的处理