Share via


How to handle app activation (HTML)

Learn how to define the activation experience for your Windows Runtime app.

Whenever your app is launched, the activated event is raised. This event can also be raised while your app is running if the system needs to pass the app parameters related to a new activation contract. You can use the activated event to restore the previous state of your app and to retrieve the activation parameters related to the contract that your app is being activated for. For a full list of the activation contracts and more details on their parameters see the ActivationKind enumeration.

The following steps will show you how to register for the activated event, use it to restore some basic app state, and use it to handle a default activation from a tile.

Instructions

Step 1: Register for the activated event

Register for the activated event in the global scope. This example sets activatedHandler as the activation handler. The activation handler enables you to retrieve the previous ApplicationExecution state of your app and the activation arguments. For a list of activation types, see the ActivationKind enumeration.


var app = WinJS.Application;

app.addEventListener("activated", activatedHandler, false);
app.start();

Step 2: Restore the application data if your app was suspended and then terminated

The operating system can terminate your app for a number of reasons after it has been suspended. Some examples of when this may happen are: the user manually closes your app, the user logs out, or the system is running low on resources. If the user launches your app after the OS has terminated it, it receives an activated event. Use the sessionState object to determine if you need to restore your app's data or start with its defaults. If your sessionState variables are defined, use them to restore the data of your app and to refresh its displayed content. If they are not defined, load the defaults.

You can also use the PreviousExecutionState property on the event args to determine whether or not your app should restore state. If this property has an ApplicationExecutionState value of Terminated you should restore state. If it is any other value you should load your app’s defaults.

Note   If your app is being activated while it is already running, you should be careful to not restore the saved data.

 

function activatedHandler(eventArgs) {
   if (eventArgs.detail.kind == Windows.ApplicationModel.Activation.ActivationKind.launch) 
   {
      // Check whether my session state variables are valid.
      // If so, retrieve the application data saved in the checkpoint handler
      if (app.sessionState) 
      {
         // TODO: Populate the UI with the previously saved application data            
      } 
      else
      {
         // TODO: Populate the UI with defaults             
      }

   }
}

Step 3: If launched on a new machine, query for existing secondary tiles

// Get secondary tile ids for the application and list them out

Windows.UI.StartScreen.SecondaryTile.findAllAsync().then(function (tiles) {
   if (tiles) {
      tiles.forEach(function (tile) {
         // Inspect the tile and do required work 
      });
   } 
   else {
      // there are no tiles 
      }
   });
}

Step 4: Retrieve the activation arguments

When the system activates your app, there may be additional context for the activation.

Each type of activation contract has its own unique set of parameters that give you more information on why your app is being activated. The eventArgs classes for each contract are defined in the Windows.UI.WebUI namespace. This code snippet shows how to retrieve arguments from a default tile launch.

function activatedHandler(eventArgs) {
    if (eventArgs.detail.kind == Windows.ApplicationModel.Activation.ActivationKind.launch) 
    {
        if (eventArgs.detail.arguments !== '')
        {
            // TODO: Parse the arguments string
        }
    // Initialize the WinJS controls
    eventArgs.setPromise(WinJS.UI.processAll();)

    }
}

Step 5: Set up app UI

When you handle the activation for an initial launch, the system will display the splash screen until your app completes activation. In some cases your app may have to do asynchronous work, such as reading settings from a file, to properly initialize its UI . This work needs to be done during activation so that the splash screen is not torn down until your UI is complete. You can defer completion of activation by using the setPromise() method on the activation eventArgs. In the previous code snippet, setPromise() is used to defer the completion of activation until the asynchronous call to processAll() is complete.

If you use the Microsoft Visual Studio templates, setPromise() is called for you. If you have asynchronous work that needs to be completed before the splash screen is torn down, complete this work during the “processed” event of your new page fragment. Make sure that you return a promise from this async activity to delay the completion of the “processed” event until the activity completes. The processed event is called whenever your app navigates to a particular page fragment so make sure any code specific to activation is only run on a navigation that is triggered by an activation. In normal navigation that code should be skipped.

Note  The splash screen is only meant to cover very brief activities that are required to set up your initial UI. Long running activities like calls to the network or loading a large file from disk should not be done during activation. In these cases your app should set up a progress UI during activation or an extended splash screen and then return from activation immediately, while the async operation continues to complete in the background.

 

processed: function (element, options) {
            // During an initial activation this event is called before activation completes.
            // Do any initialization work that is required for the initial UI to be complete.
            // Retrieve settings from a file
            return app.local.readText(settingsFile, "default").then(function (str){
                //use the settings to update the UI
            }, function () {
                //handle the error condition
               });
           },

ready:     function (element, options) {
            // During an initial activation this event is called after activation completes.
            // Do any initialization work that is not related to getting the initial UI set up.
           }

Remarks

When the app is launched, the activated event is raised after the DOMContentLoaded event and before the WinJS.Application.onloaded event. While the app is running, activated events may be raised at any time.

Note  If your app needs to navigate the top level document for any reason you must first complete activation before attempting to do the top level navigation. If you attempt a top level navigation before activation completes your app will crash. This ensures that your app and the system are in a consistent state before the JavaScript context is torn down and recreated during the navigation.

 

Note  

For Windows Phone Store apps, the resuming event is always followed by the activated event, even when your app is currently suspended and the user re-launches your app from a primary tile or app list. Apps can skip initialization if there is already content set on the current window. You can check the LaunchActivatedEventArgs.TileId property to determine if the app was launched from a primary or a secondary tile and, based on that information, decide whether you should present a fresh or resume app experience.

Complete example

See the App activate and suspend using WinJS sample and the App activated, resume, and suspend using the WRL sample for complete code examples showing how to handle app lifecycle events.

Tasks

How to suspend an app

How to resume an app

Conceptual

Application lifecycle

Reference

Windows.ApplicationModel.Activation.ActivationKind

Windows.UI.WebUI.WebUILaunchActivatedEventArgs

WinJS.Application.activated