Simple way to poll server from Xamarin.Forms client

Hi there
I have to implement a polling code to send a device App status to a server (I use WCF) and get a command from the server to be executed (if at all).
It polls each, say, 10 seconds regardless whether the app commands the screen or the device is hibernating (I mean it screen gets black while it left untouched for a time).
Can I just attach my PollingTimerClass to the Application.Current and start it in OnStart() event handler?
Again, it must poll when:
1. Application is active
2. Application is not active. It is pushed by another application on the screen
3. Device is a black screen, but it is not off

Thanks.

Posts

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    @NickRenzhiglov I use this method to have a timer that poll every X seconds. It is closed when the app goes to background and restart on "OnRestart". I think you can take a look, just to start.

    public class App : Application
    {
        public static CancellationTokenSource CancellationToken { get; set; }
        private Label _label = new Label();
    
        public App ()
        {
    
            ContentPage cp = new ContentPage ();
            StackLayout sl = new StackLayout ();
            _label.FontSize = 30;
            sl.Children.Add (_label);
            cp.Content = sl;
            MainPage = cp;
            return;
    
        }
    
        protected override void OnStart ()
        {
            // Handle when your app starts
            Task.Run (async() => timer ());
        }
    
        private int _counter = 0;
        private async  Task timer(){
    
            App.CancellationToken = new CancellationTokenSource ();
            while (!App.CancellationToken.IsCancellationRequested)
            {
                try
                {
                    //await Task.Delay(60000 - (int)(watch.ElapsedMilliseconds%1000), token);
                    App.CancellationToken.Token.ThrowIfCancellationRequested();
                    await Task.Delay(1000 , App.CancellationToken.Token).ContinueWith(async (arg) =>{
    
                        if (!App.CancellationToken.Token.IsCancellationRequested) {
                            App.CancellationToken.Token.ThrowIfCancellationRequested();
                            /*
                             * HERE YOU CAN DO YOUR ACTION
                             */
    
                            var locator = CrossGeolocator.Current;
                            locator.DesiredAccuracy = 50;
    
                            var position = await locator.GetPositionAsync (timeoutMilliseconds: 10000);
    
                            Debug.WriteLine ("Position Status: {0}", position.Timestamp);
                            Debug.WriteLine ("Position Latitude: {0}", position.Latitude);
                            Debug.WriteLine ("Position Longitude: {0}", position.Longitude);
    
                            Device.BeginInvokeOnMainThread(()=> _label.Text = (++_counter).ToString());
                            Debug.WriteLine ("TimerRunning " + _counter.ToString() + " " + position.Latitude + " " + position.Longitude);// + watch.Elapsed.ToString ());
                        }
                    });
                    //Debug.WriteLine (DateTime.Now.ToLocalTime ().ToString () + " DELAY: " + delay);
    
                }
                catch (Exception ex)
                {
                    Debug.WriteLine ("EX 1: " + ex.Message);
                }
            }
        }
    
        protected override void OnSleep ()
        {
            // Handle when your app sleeps
            if (App.CancellationToken != null) {
                App.CancellationToken.Cancel ();
                //App.CancellationToken = null;
            }
        }
    
        protected override void OnResume ()
        {
            // Handle when your app resumes
            Task.Run (async() => timer ());
        }
    }
    
  • NickRenzhiglovNickRenzhiglov CAMember ✭✭

    Hi there
    No suggestions? It looks like the App thread stops when I switch to a different App and there is no way to leave my software polling on a background.
    May be there are Android/iOS platform specific ways to implement it?
    Thanks.

  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    Android you would want to create a Service to run.

    iOS uses beginBackgroundTask, and there are specific types of things you can have run. See this for how to do background tasks.

  • JulienRosenJulienRosen CAMember ✭✭✭✭

    I think you should have a fresh look at your project design. Mobile apps are not designed to run custom code while backgrounded. Google and Apple do provide some ability but they are hard coded and not meant to allow things like polling.

  • NickRenzhiglovNickRenzhiglov CAMember ✭✭

    Google and Apple do provide some ability

    As per Google, you are probably talking about Google Cloud Messaging (not sure about the exact name). It is not the same what I need. The Google Cloud Messaging concentrates and sends messages only if the client let (i.e. launch the client's application).
    I need it to be notified whenever possible if only the device is on (like the telephone ring or SMS does).
    Any clue?
    Thanks.

  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    As I said, a service on Android gets the job done. Can be run in the background, with or without your app open, indefinitely.

  • NickRenzhiglovNickRenzhiglov CAMember ✭✭

    Hi AdamMeaney
    I'll dig into the Android service for sure. For iOS, as far as I know they reluctant to approve the project with such "background" functionality. If it is not a viable solution for both, it is not worthwhile to go that "polling" way, I believe.
    I'm going to consider the SMS way instead.
    Thank you guys for your advices.

  • srikant460srikant460 AUMember ✭✭

    Hi i'm stuck with the same problem as your's.
    When you say "I'm going to consider the SMS way instead." does it mean a push notification from the server?

    If not, then what was your approach. Any response is much appreciated. Thanks.

  • NickRenzhiglovNickRenzhiglov CAMember ✭✭

    Srikant460
    Since the SMS client is kind of out-of-box functionality, I sent SMS to from a server to a user's phone number. This allows no care about what the way the phone is used. It can be even off by the moment the SMS arrives. But this is by the cost of the using of the SMS aggregator service (I use CDYNE http://wiki.cdyne.com/index.php/Main_Page)
    The latter is more business, not a programming aspect.
    CDYNE accepts both SMS/Phone and any kind of scripts to pick up the user's response. Wicked cool.
    I hope this helps.
    Thanks.

Sign In or Register to comment.