Thursday, September 8, 2011

Life Cycle in Windows Phone 7

This is a sample for saving and restoring your state on deactivation and reactivation respectively. The follow code is a copy from my App.xaml.cs file.

// Code to execute when the application is launching (eg, from Start)

// This code will not execute when the application is reactivated

private void Application_Launching(object sender, LaunchingEventArgs e)

{

    LoadStates();

}

 

// Code to execute when the application is activated (brought to foreground)

// This code will not execute when the application is first launched

private void Application_Activated(object sender, ActivatedEventArgs e)

{

    LoadStates();

}

 

// Code to execute when the application is deactivated (sent to background)

// This code will not execute when the application is closing

private void Application_Deactivated(object sender, DeactivatedEventArgs e)

{

    SaveState();

}

 

// Code to execute when the application is closing (eg, user hit Back)

// This code will not execute when the application is deactivated

private void Application_Closing(object sender, ClosingEventArgs e)

{

    SaveState();

}

 

// Save the states of this application

private void SaveState()

{

    PhoneApplicationService phoneAppService = PhoneApplicationService.Current;

    IsolatedStorageSettings isoSettings = IsolatedStorageSettings.ApplicationSettings;

 

    if (phoneAppService.State.ContainsKey("userCulture"))

        isoSettings["userCulture"] = phoneAppService.State["userCulture"];

    if (phoneAppService.State.ContainsKey("memory"))

        isoSettings["memory"] = phoneAppService.State["memory"];

}

 

// Load the states of this application

private void LoadStates()

{

    PhoneApplicationService phoneAppService = PhoneApplicationService.Current;

    IsolatedStorageSettings isoSettings = IsolatedStorageSettings.ApplicationSettings;

 

    string isoSettingString ="";

    if (isoSettings.TryGetValue<string>("userCulture", out isoSettingString))

        phoneAppService.State["userCulture"] = isoSettingString;

    isoSettingString =""; // Initial it again.

    double isoSettingDouble = 0.0;

    if(isoSettings.TryGetValue<double>("memory", out isoSettingDouble))

        phoneAppService.State["memory"] = isoSettingDouble;

}

 

Userful articles:

No comments:

Post a Comment