Xamarin表单后台委托称为

时间:2017-02-22 12:20:21

标签: xamarin.android xamarin.forms

我目前正在使用connectivity plugin来检测网络状态。我想要做的是当我想发送数据并且设备处于离线状态时,我使用消息服务和相应的平台特定代码启动后台任务,如here所示。

我遇到的问题是Android服务有一个回调,即使在我停止服务后仍会继续调用。下面的代码将委托分配给CrossConnectivity.Current.ConnectivityChanged,并且应该在网络连接恢复后发送所需数据后停止服务。

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
    ...
    Task.Run(() =>
                {
                    CrossConnectivity.Current.ConnectivityChanged += delegate
                    {
                        if (CrossConnectivity.Current.IsConnected)
                        {          
                            if (!App.ServerManager.IsUserLoggedIn())
                            App.ServerManager.LoginUserAsync(Constants.__User);

                        //send our data
                        foreach (SampleItem s in sList)
                        {
                           try 
                           {
                               //query to see if it exists on the server
                               App.ServerManager.GetSamplesAsync();

                               Task t = App.ServerManager.SaveSampleAsync(s);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(@"                ERROR {0}", e.Message);
                            }
                        }
                        // Instantiate the builder and set notification elements:
                        Notification.Builder builder = new Notification.Builder(this)
                        .SetContentTitle("Jarver Industries")
                        .SetContentText("Samples Successfuly Sent!")
                        .SetDefaults(NotificationDefaults.Sound)
                        .SetSmallIcon(Resource.Drawable.banner);

                        // Build the notification:
                        Notification notification = builder.Build();

                        // Get the notification manager:
                        NotificationManager notificationManager =
                        GetSystemService(Context.NotificationService) as NotificationManager;

                        // Publish the notification:
                        const int notificationId = 19900203;
                        notificationManager.Notify(notificationId, notification);
                        MessagingCenter.Send<BackgroundDataFinishedMessage>(this, "Done");
                        StopSelf();
                        }
                    };
                });
    return StartCommandResult.Sticky;
}

我确信我在.NET级别上做错了什么,但我不确定有什么替代方案。

0 个答案:

没有答案