Handling Interruptions on Windows Phone

On Windows Phone, your game can be shut down at any time due to a number of events, such as:

  • A call, text message, or other top-level communication comes in, and the user decides to take it.
  • The user presses the phone's Home button while the game is running.
  • The user turns off the phone while the game is running.
  • The phone turns itself off because the user did not provide input within the system-wide timeout period.

To handle these interruptions, care must be taken to make sure that your game responds in a predictable way, and that game data is not lost.

Complete Sample

The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Download Sample Code

To handle game interruptions on Windows Phone:

  1. Override Game.OnExiting in your Game class.

  2. When Game.OnExiting is called, save any game data necessary to restart the game in its current state to the game's isolated storage. For example:

    protected override void OnExiting(object sender, System.EventArgs args)
    {
        // Save the game state (in this case, the typed text).
        IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
    
        // open isolated storage, and write the savefile.
        IsolatedStorageFileStream fs = null;
        fs = savegameStorage.OpenFile(SAVEFILENAME, System.IO.FileMode.Create);
        if (fs != null)
        {
            // just overwrite the existing info for this example.
            fs.WriteByte(gameState); // a single byte
            if ((typedText != null) && (typedText.Length > 0))
            {
                fs.Write(System.Text.Encoding.UTF8.GetBytes(typedText), 0, typedText.Length);
            }
            fs.Close();
        }
    
        base.OnExiting(sender, args);
    }
    
  3. Handle the PhoneApplicationService.Activated event to detect when an application is resuming after having been interrupted. For example:

    bool isActivated = false;
    
    public Game1()
    {
        Microsoft.Phone.Shell.PhoneApplicationService service = Microsoft.Phone.Shell.PhoneApplicationService.Current;
        service.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(service_Activated);
    }
    
    void service_Activated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
    {
        isActivated = true;
    }
    

    Note

    To work with this event, you'll need to add the Microsoft.Phone assembly to your project's references. You can do this in Visual Studio by right-clicking References in Solution Explorer, and then clicking Add Reference.

  4. In your game's constructor or initialization methods, look for the presence of saved game data in the game's isolated storage, and if found, restore the game's state. For example:

    protected override void Initialize()
    {
        gameState = 0;
    
        IsolatedStorageFile savegameStorage = IsolatedStorageFile.GetUserStoreForApplication();
    
        // open isolated storage, and write the savefile.
        if(savegameStorage.FileExists(SAVEFILENAME))
        {
            IsolatedStorageFileStream fs = null;
            try
            {
                fs = savegameStorage.OpenFile(SAVEFILENAME, System.IO.FileMode.Open);
            }
            catch (IsolatedStorageException e)
            {
                // The file couldn't be opened, even though it's there.
                // You can use this knowledge to display an error message
                // for the user (beyond the scope of this example).
            }
    
            if (fs != null)
            {
                // Reload the last state of the game.  This consists of the UI mode
                // and any text that was typed on the keyboard input screen. 
                byte[] saveBytes = new byte[256];
                int count = fs.Read(saveBytes, 0, 256);
                if (count > 0)
                {
                    // the first byte is the mode, the rest is the string.
                    gameState = saveBytes[0];
                    if (count > 1)
                    {
                        typedText = System.Text.Encoding.UTF8.GetString(saveBytes, 1, count - 1);
                    }
                    fs.Close();
                }
            }
        }
    
        base.Initialize();
    }
    
  5. If the PhoneApplicationService.Activated event was fired, you can bypass initial menus and start the player immediately in the state recorded in the save file. For example:

    bool isActivated = false;
    
    public Game1()
    {
        Microsoft.Phone.Shell.PhoneApplicationService service = Microsoft.Phone.Shell.PhoneApplicationService.Current;
        service.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(service_Activated);
    }
    
    void service_Activated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
    {
        isActivated = true;
    }
    
    Ff827866.bp(en-us,XNAGameStudio.40).gifBest Practice
    When restoring a game that has been re-activated, you should return the player to whatever mode or screen he or she was working with when the game was interrupted. If the game is not being re-activated, but re-launched instead, you can start the player at the main menu, adding an option to restore the game to the saved position.

For more information about using isolated storage on Windows Phone, see Writing Data (Windows Phone).

Testing Game Reactivation

You can test game reactivation in the Windows Phone Emulator, or using a Windows Phone device.

To test game reactivation

Run your game in the debugger on the emulator or phone.

When the game is running, press the Home button on the emulator or phone.

Press the Back button on the emulator or phone to reactivate the game without relaunching it.

Note

If you re-launch the game by tapping its icon on the phone, or press F5 to restart debugging in Visual Studio, the game will not fire the PhoneApplicationService.Activated event.

See Also

Concepts

Windows Phone Programming

Topics in the Windows Phone Documentation

  • Execution Model Overview for Windows Phone

    Under the Windows Phone execution model, applications are activated and deactivated dynamically when a user navigates away from the application. This document describes how to persist data correctly for a windows phone application when the application is activated or deactivated.

  • Execution Model Best Practices for Windows Phone

    Windows Phone applications are terminated when the user navigates away from them. This topic highlights some best practices for handling execution model events.