locked
How to resume timer after suspending or terminated?

    Question

  • Hi,

    I am trying to understand the suspend.

    I made a little game:
    Hit a bottom several times.

    Every time the score increase with 1.

    When timer is 12 seconds and score is less than
    10 message:
    Time Over! You lose!

    When timer is less than 12 and you  hit
     10 times message:
    You Won! You score 10 hits.

    I made a small project and I uploaded.

    The project has a button:  Hit Me!
    2 textblocks : Timer and Score
    2 buttons: Start and Stop used to
    understand  DispatcherTimer dispatcherTimer

    What I want is When I suspend the app at timeStop second
    for example at sec 5, When I resume must to be at 5 same
    thing with score.

    If I terminate by closing the app I will put the when I suspend
    the timeStop in 
     Windows.Storage.ApplicationDataContainer roamingSettings =
                               Windows.Storage.ApplicationData.Current.RoamingSettings;

    WHen I started if is for the first time I read from roamingSettings
    if not I read values form suspendState.

    Other problem is when I hit New button I am able to make timer 0,
    but in the next step it is not 0 it starts from the last value.
    The link to download is
    https://onedrive.live.com/redir?resid=857BC62170EDDB22!3259&authkey=!AHOByBYgD94fEEQ&ithint=file%2c.zip

    Please help me.
    Thanks


    ADRIAN DIBU

    Monday, July 7, 2014 2:00 AM

Answers

  • Hi ADRIAN,

    Thanks for your project.

    I would suggest you to read this: How to resume an app., when you resume the app, there is no event fires and of course you cannot update anything in UI, here we add a event for Resuming action.

    You may add following lines to your code to ensure that the tick works fine.

            public MainPage()
            {
                ......
                Application.Current.Resuming += new EventHandler<Object>(App_Resuming);
             
            }
            private void App_Resuming(object sender, object e)
            {
    
                dispatcherTimer.Start();
                // you should do something here to update the text for seconds displayed
            }

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.


    Wednesday, July 9, 2014 10:17 AM
    Moderator
  • Hi ADRIAN,

    I'm not see any event that you can fire the SaveState method, I think that should be the reason why you cannot save data.

    Let's say if you would like to save the data when the app about to suspend, you can also register a event for suspend:

                Application.Current.Resuming += new EventHandler<Object>(App_Resuming);
                Application.Current.Suspending += Current_Suspending;
    

    Put your SaveState method code into the Current_Suspending event should be fine.

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Friday, July 11, 2014 3:47 AM
    Moderator
  • Hi,
    Thanks for help.
     Now buttons New, Reset, Stop, Start, Hit Me! and Navigate
    works.
     If you find a scenario it don't work, let me know.
     Please test it and use it if you like it.
    The Link:
    https://onedrive.live.com/redir?resid=857BC62170EDDB22!3275&authkey=!ABV38P_5oXuCtYs&ithint=file%2c.zip

    Best regards


    ADRIAN DIBU

    Friday, July 18, 2014 1:02 PM

All replies

  • Hi ADRIAN,

    Your package contain some third party SDK like SQLite and I cannot successfully run it.

    However I think I know what you mean by your description. The DispatcherTimer should start from the certain second correct?

    That could be easy, let's say you suspend the app at 7 second, and when you back to the app, you have to add a statement in your code, something like compare the deadline time (12 second) with the current dispatch Time (5 second) plus the second you saved (7 second).

    in your line 290:

    //timeSaved is the time that you saved when the app suspend.
    if (timesTicked + timeSaved > timesToTick)
    {
    ...
    }

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.


    Tuesday, July 8, 2014 9:18 AM
    Moderator
  • Hi,

    Thanks for trying to help me.
    I uploaded the project without SQLite refences and Ad and fixed parts.
    I hope it will work to be able to understand what I want.

    Now I can to suspend but I can't start timer when I resume and I can't make it
    start with data from roamingSetting.

    The link:

    https://onedrive.live.com/redir?resid=857BC62170EDDB22!3266&authkey=!ALTHkTQbA21x3UI&ithint=file%2c.zip

    Thanks


    ADRIAN DIBU

    Tuesday, July 8, 2014 4:05 PM
  • Hi ADRIAN,

    Thanks for your project.

    I would suggest you to read this: How to resume an app., when you resume the app, there is no event fires and of course you cannot update anything in UI, here we add a event for Resuming action.

    You may add following lines to your code to ensure that the tick works fine.

            public MainPage()
            {
                ......
                Application.Current.Resuming += new EventHandler<Object>(App_Resuming);
             
            }
            private void App_Resuming(object sender, object e)
            {
    
                dispatcherTimer.Start();
                // you should do something here to update the text for seconds displayed
            }

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.


    Wednesday, July 9, 2014 10:17 AM
    Moderator
  • Hi,

    Thanks for help.

    I fixed a lot of parts.

    I still have a problem I can't SaveState

    private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
            {
                System.Diagnostics.Debug.WriteLine("In navigationHelper_SaveState timeStop.ToString(): " + timeStop.ToString());
                System.Diagnostics.Debug.WriteLine("In navigationHelper_SaveState txtScore.Text: " + txtScore.Text);
            
             //   timeStop = System.Convert.ToInt32(timesTicked.ToString());

                roamingSettings.Values["MyValueTimeStop"] = timeStop.ToString(); // timesTicked.ToString();
                roamingSettings.Values["MyValueScore"] = txtScore.Text;


                e.PageState["MyValueTimeStopS"] = timeStop.ToString(); // timesTicked.ToString();
                e.PageState["MyValueScoreS"] = txtScore.Text;
                if (App.isSuspended == true)
                {
                    dispatcherTimer.Stop();
                }
       
            }
     public MainPage()
            {
                this.InitializeComponent();
           
                this.navigationHelper = new NavigationHelper(this);
                this.navigationHelper.LoadState += navigationHelper_LoadState;
                this.navigationHelper.SaveState += navigationHelper_SaveState;

                Application.Current.Resuming += new EventHandler<Object>(App_Resuming);

                var b = Window.Current.Bounds;
                if (b.Height > b.Width)
                {
                    OutputA.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    OutputB.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            
                    panelMain.Width = 768;
                }
                else
                {
                    OutputA.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    OutputB.Visibility = Windows.UI.Xaml.Visibility.Visible;
              
                    panelMain.Width = 1366;
                }

                 dispatcherTimer = new DispatcherTimer();
                 dispatcherTimer.Tick += dispatcherTimer_Tick;
                 dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

                 if (App.mainPageFirstLoad == true)
                 {
                     timeStop = System.Convert.ToInt32(App.pTimeStop.ToString());
                     Score = System.Convert.ToInt32(App.pScore.ToString());
                     App.mainPageFirstLoad = false;
                 }
                 else
                 {
                     if (roamingSettings.Values.ContainsKey("MyValueTimeStop"))
                     {
             
                         timeStop = System.Convert.ToInt32(roamingSettings.Values["MyValueTimeStop"].ToString());
                     }
                     else
                     {
                         timeStop = 0;
                     }
                     if (roamingSettings.Values.ContainsKey("MyValueScore"))
                     {
                         Score = System.Convert.ToInt32(roamingSettings.Values["MyValueScore"].ToString());
               
                     }
                     else
                     {
                         Score = 0;
                     }

                 }
                 dispatcherTimer.Start();    
            }

    The link is
    https://onedrive.live.com/redir?resid=857BC62170EDDB22!3267&authkey=!AJeGqhR-rckML1A&ithint=file%2c.zip


    ADRIAN DIBU

    Wednesday, July 9, 2014 3:46 PM
  • Hi ADRIAN,

    I'm not see any event that you can fire the SaveState method, I think that should be the reason why you cannot save data.

    Let's say if you would like to save the data when the app about to suspend, you can also register a event for suspend:

                Application.Current.Resuming += new EventHandler<Object>(App_Resuming);
                Application.Current.Suspending += Current_Suspending;
    

    Put your SaveState method code into the Current_Suspending event should be fine.

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Friday, July 11, 2014 3:47 AM
    Moderator
  • Hi,

    Thanks for the prompt answer. 

    I suppose to navigate to have

    private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)

    So I added a button btnNavigate to see what happen.

    I made a lot of fixes, it almost works, but when I navigate back to MainPage seconds are not OK.

    Please take a look

    Thanks

     

    The new link is

    https://onedrive.live.com/redir?resid=857BC62170EDDB22!3268&authkey=!AFGBf22WFNPSkmA&ithint=file%2c.zip

    ADRIAN DIBU

    Friday, July 11, 2014 3:34 PM
  • Hi,

    What I need is:

    To check in roamingSettings if MyValueTimeStop exists
    if true:
    the app was closed before game finish, so I must read
    MyValueTimeStop and in MainPage when mainPageFirstLoad is true
    to start dispatcherTimer from the value.
    if false:
    the app is for the first time started mainPageFirstLoad is true
    must start dispatcherTimer from 0.
    Now:
    if I make 10 hits in less than 12 seconds
    message "You Won!" and in roamingSettings MyValueTimeStop = 0

    if I don't make 10 hits in less than 12 seconds
    message "Time Over!" and in roamingSettings MyValueTimeStop = 0

    if navigate to other page I used
    navigationHelper_SaveState to save the time in
    e.PageState["MyValueTimeStopS"]
    and App.isSuspended = true;
    dispatcherTimer.Stop()
    to prevent a close during navigation I saved

    when I navigate back to MainPage I read
    MyValueTimeStopS with navigationHelper_LoadState
    App.isSuspended = false;
    and I start dispatcherTimer from MyValueTimeStopS.
    dispatcherTimer.Start()

    Can sombody tell me if I am wrong ?


    ADRIAN DIBU

    Saturday, July 12, 2014 2:55 PM
  • Hello adibu,

    You issue sounds like a logical issue, I would suggest you to go review your code and check the logical stuff. You already know how to save the data, read the data, how to do something while app suspend and how to execute code when app resume, it should not be a difficult thing to implement your app.

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Monday, July 14, 2014 8:21 AM
    Moderator
  • Hi,

    Thanks for the prompt answer.

    It is not clear what happen when I navigate (it seams to me the app is suspended
    and I am able to read using navigationHelper_LoadState write using navigationHelper_SaveState)
    and when the app is suspended because of switching I don't know what to do with timeStop
     
    void dispatcherTimer_Tick(object sender, object e)
    {
               if (App.isSuspended == false)
                {
                    timesTicked++;
                    TimerLog.Text = TimeToString(timesTicked - timeStop);
                }
    }

    dispatcherTimer_Tick are working only run up with no reset so I am forced to do
    TimerLog.Text = TimeToString(timesTicked - timeStop);

    I think I need to introduce:
    1)
    private bool isTimeStopForced ;
    private int timeStopForceed;

    for the case when app is closed and not reached 10 hits I save timeStopForceed in
    roamingSettings
    Now when I load the app I am looking if timeStopForceed > 0 if so

      dispatcherTimer = new DispatcherTimer();
      dispatcherTimer.Tick += dispatcherTimer_Tick;
      dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
      dispatcherTimer.Start();

      TimerLog.Text = TimeToString(timesTicked + timeStopForced);
    2)
    private bool isTimeStopNavigate ;
    private int timeStopNavigate;

    for case of navigation I save timeStopNavigate in roamingSettings as MyValueTimeStopNavigate
    for case of forced close
    and timeStopNavigateS with navigationHelper_SaveState as MyValueTimeStopNavigateS.
    I must suspend the app end 
    dispatcherTimer.Stop()
    timeStopNavigate = timesTicked
    App.isSuspended = true

    Now what I am doing if in navigated Page I need the app not to be suspended????

    When I navigate back; 
    dispatcherTimer.Start()
    App.isSuspended == false
    TimerLog.Text = TimeToString(timesTicked); when I start it run from the last tick.
    or
     dispatcherTimer = new DispatcherTimer();
      dispatcherTimer.Tick += dispatcherTimer_Tick;
      dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
      dispatcherTimer.Start();

     TimerLog.Text = TimeToString(timesTicked + System.Convert.ToInt32e.PageState["MyValueTimeStopNavigateS"].ToString()));
    Tell me please if the logic is good.
    Thanks


    ADRIAN DIBU

    Tuesday, July 15, 2014 12:43 AM
  • Hi,
    Thanks for help.
     Now buttons New, Reset, Stop, Start, Hit Me! and Navigate
    works.
     If you find a scenario it don't work, let me know.
     Please test it and use it if you like it.
    The Link:
    https://onedrive.live.com/redir?resid=857BC62170EDDB22!3275&authkey=!ABV38P_5oXuCtYs&ithint=file%2c.zip

    Best regards


    ADRIAN DIBU

    Friday, July 18, 2014 1:02 PM
  • OH, great to hear that, congratulations. You can even upload to Code Center for sharing the project :)

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Saturday, July 19, 2014 2:01 AM
    Moderator