简体   繁体   中英

How to calculate the total time a user spending on a WP7 silverlight application?

I need to save to an isolated storage the total time that the user spent on an application.

I think I should know the time of starting and finishing execution.

If there is any way to do that please..

Thanks..

There are couple methods in the App.xaml.cs file that are directly related to the execution model:

  • Application_Launching
  • Application_Activated
  • Application_Deactivated
  • Application_Closing

You can hook this methods and provide there needed logic which, actually, is pretty straightforward:

  • Application_Launching - initialize spentTime ;
  • Application_Activated - restore spentTime from State ;
  • Application_Deactivated - recalculate time and store to State to be able to get it further;
  • Application_Closing - recalculate and store spentTime to Isolated Storage .


Some useful links for understanding WP Execution Model:

To add to AnatoliiG's answer, you can use the DispaterTimer class to calculate the time. Be careful using DateTime.Now to calculate the time the user has been using the app as there are times during the year where this will give you bad values.

private _DispatcherTimer _timer;
private int _spentTime;

public Application()
{
    _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
    _timer.Tick += TimerTick;
}

TimerTick(object s, EventArgs args)
{
    _spentTime++;
}

Then follow AnatoliiG example to save the time spent at the different events.

private void Application_Launching(object sender, LaunchingEventArgs e)
{
    _timer.Start();
    // Should probably have some logic to determine if they tombstoned the app
    // and did not actually leave the app, if so then save that time
}

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    _timer.Start();
    // Restore _spentTime
}

private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
    _timer.Stop();
    // Store _spentTime
}

private void Application_Closing(object sender, ClosingEventArgs e)
{
    // Save time, they're done!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM