Background tasks

Hi All,

I am currently using the connectivity plugin to detect network status. What I am trying to do is when I want to send data and the device is offline I start a background task using the messaging service and respective platform specific code as shown here.

The problem I am having is the Android service has a callback that continues being called even after I have stopped the service. The code below assigns a delegate to the CrossConnectivity.Current.ConnectivityChanged and should stop the service when network connection is restored.

 public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
 {
    ...
    Task.Run(() =>
                {
                    CrossConnectivity.Current.ConnectivityChanged += delegate
                    {
                        if (CrossConnectivity.Current.IsConnected)
                        {                   
                            ...
                            //send data
                ...
                            StopSelf();
                        }
                    };
                });
    return StartCommandResult.Sticky;
}

I am sure I am doing something wrong on a .NET level, but I am unsure what alternatives there are.

Best Answer

  • DanysChalifourDanysChalifour US ✭✭
    edited April 2017 Accepted Answer
    1. Keep a reference to your delegate
    2. Throw a Callback function inside your delegate
    3. Unnasign your delegate in the callback Function like so:
      CrossConnectivity.Current.ConnectivityChanged -= YOUR_DELEGATE

Answers

  • MichaelVowlesMichaelVowles USMember ✭✭

    Sorry to bump but @JamesMontemagno, did you have any thoughts?

  • DanysChalifourDanysChalifour USMember ✭✭
    edited April 2017 Accepted Answer
    1. Keep a reference to your delegate
    2. Throw a Callback function inside your delegate
    3. Unnasign your delegate in the callback Function like so:
      CrossConnectivity.Current.ConnectivityChanged -= YOUR_DELEGATE
  • DanysChalifourDanysChalifour USMember ✭✭

    Mark as solved anytime soon

Sign In or Register to comment.