Gestire l’attivazione dell’appHandle app activation

Informazioni su come gestire l'attivazione dell'app eseguendo l'override del metodo Application. OnLaunched .Learn how to handle app activation by overriding the Application.OnLaunched method.

Eseguire l'override del gestore degli avviiOverride the launch handler

Quando viene attivata un'app, per qualsiasi motivo il sistema invia l'evento CoreApplicationView. Activated .When an app is activated, for any reason, the system sends the CoreApplicationView.Activated event. Per un elenco di tipi di attivazione, vedere l’enumerazione ActivationKind.For a list of activation types, see the ActivationKind enumeration.

La classe Windows.UI.Xaml.Application definisce i metodi di cui puoi eseguire l’override per gestire i vari tipi di attivazione.The Windows.UI.Xaml.Application class defines methods you can override to handle the various activation types. Alcuni tipi di attivazione prevedono un metodo specifico di cui puoi eseguire l'override.Several of the activation types have a specific method that you can override. Per gli altri tipi di attivazione, eseguire l'override del metodo OnActivated .For the other activation types, override the OnActivated method.

Definisci la classe per l'applicazione.Define the class for your application.

<Application
    x:Class="AppName.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

Eseguire l'override del metodo OnLaunched .Override the OnLaunched method. Questo metodo viene chiamato ogni volta che l'utente avvia l'app.This method is called whenever the user launches the app. Il parametro LaunchActivatedEventArgs contiene lo stato precedente dell'app e gli argomenti di attivazione.The LaunchActivatedEventArgs parameter contains the previous state of your app and the activation arguments.

Nota

In Windows, l'avvio di un'app sospesa dal riquadro iniziale o dall'elenco di app non chiama questo metodo.On Windows, launching a suspended app from Start tile or app list doesn't call this method.

using System;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;

namespace AppName
{
   public partial class App
   {
      async protected override void OnLaunched(LaunchActivatedEventArgs args)
      {
         EnsurePageCreatedAndActivate();
      }

      // Creates the MainPage if it isn't already created.  Also activates
      // the window so it takes foreground and input focus.
      private MainPage EnsurePageCreatedAndActivate()
      {
         if (Window.Current.Content == null)
         {
             Window.Current.Content = new MainPage();
         }

         Window.Current.Activate();
         return Window.Current.Content as MainPage;
      }
   }
}
Class App
   Protected Overrides Sub OnLaunched(args As LaunchActivatedEventArgs)
      Window.Current.Content = New MainPage()
      Window.Current.Activate()
   End Sub
End Class
...
#include "MainPage.h"
#include "winrt/Windows.ApplicationModel.Activation.h"
#include "winrt/Windows.UI.Xaml.h"
#include "winrt/Windows.UI.Xaml.Controls.h"
...
using namespace winrt;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;

struct App : AppT<App>
{
    App();

    /// <summary>
    /// Invoked when the application is launched normally by the end user.  Other entry points
    /// will be used such as when the application is launched to open a specific file.
    /// </summary>
    /// <param name="e">Details about the launch request and process.</param>
    void OnLaunched(LaunchActivatedEventArgs const& e)
    {
        Frame rootFrame{ nullptr };
        auto content = Window::Current().Content();
        if (content)
        {
            rootFrame = content.try_as<Frame>();
        }

        // Do not repeat app initialization when the Window already has content,
        // just ensure that the window is active
        if (rootFrame == nullptr)
        {
            // Create a Frame to act as the navigation context and associate it with
            // a SuspensionManager key
            rootFrame = Frame();

            rootFrame.NavigationFailed({ this, &App::OnNavigationFailed });

            if (e.PreviousExecutionState() == ApplicationExecutionState::Terminated)
            {
                // Restore the saved session state only when appropriate, scheduling the
                // final launch steps after the restore is complete
            }

            if (e.PrelaunchActivated() == false)
            {
                if (rootFrame.Content() == nullptr)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(xaml_typename<BlankApp1::MainPage>(), box_value(e.Arguments()));
                }
                // Place the frame in the current Window
                Window::Current().Content(rootFrame);
                // Ensure the current window is active
                Window::Current().Activate();
            }
        }
        else
        {
            if (e.PrelaunchActivated() == false)
            {
                if (rootFrame.Content() == nullptr)
                {
                    // When the navigation stack isn't restored navigate to the first page,
                    // configuring the new page by passing required information as a navigation
                    // parameter
                    rootFrame.Navigate(xaml_typename<BlankApp1::MainPage>(), box_value(e.Arguments()));
                }
                // Ensure the current window is active
                Window::Current().Activate();
            }
        }
    }
};
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::Foundation;
using namespace Windows::UI::Xaml;
using namespace AppName;
void App::OnLaunched(LaunchActivatedEventArgs^ args)
{
   EnsurePageCreatedAndActivate();
}

// Creates the MainPage if it isn't already created.  Also activates
// the window so it takes foreground and input focus.
void App::EnsurePageCreatedAndActivate()
{
    if (_mainPage == nullptr)
    {
        // Save the MainPage for use if we get activated later
        _mainPage = ref new MainPage();
    }
    Window::Current->Content = _mainPage;
    Window::Current->Activate();
}

Ripristinare i dati applicazione quando l'app è stata sospesa e quindi chiusaRestore application data if app was suspended then terminated

Quando l’utente passa all’app chiusa, il sistema invia l’evento Activated, con Kind impostato su Launch e PreviousExecutionState impostato su Terminated o ClosedByUser.When the user switches to your terminated app, the system sends the Activated event, with Kind set to Launch and PreviousExecutionState set to Terminated or ClosedByUser. L'app deve caricare i dati applicazione salvati e aggiornare il contenuto visualizzato.The app should load its saved application data and refresh its displayed content.

async protected override void OnLaunched(LaunchActivatedEventArgs args)
{
   if (args.PreviousExecutionState == ApplicationExecutionState.Terminated ||
       args.PreviousExecutionState == ApplicationExecutionState.ClosedByUser)
   {
      // TODO: Populate the UI with the previously saved application data
   }
   else
   {
      // TODO: Populate the UI with defaults
   }

   EnsurePageCreatedAndActivate();
}
Protected Overrides Sub OnLaunched(args As Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
   Dim restoreState As Boolean = False

   Select Case args.PreviousExecutionState
      Case ApplicationExecutionState.Terminated
         ' TODO: Populate the UI with the previously saved application data
         restoreState = True
      Case ApplicationExecutionState.ClosedByUser
         ' TODO: Populate the UI with the previously saved application data
         restoreState = True
      Case Else
         ' TODO: Populate the UI with defaults
   End Select

   Window.Current.Content = New MainPage(restoreState)
   Window.Current.Activate()
End Sub
void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs const& e)
{
    if (e.PreviousExecutionState() == ApplicationExecutionState::Terminated ||
        e.PreviousExecutionState() == ApplicationExecutionState::ClosedByUser)
    {
        // Populate the UI with the previously saved application data.
    }
    else
    {
        // Populate the UI with defaults.
    }
    ...
}
void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args)
{
   if (args->PreviousExecutionState == ApplicationExecutionState::Terminated ||
       args->PreviousExecutionState == ApplicationExecutionState::ClosedByUser)
   {
      // TODO: Populate the UI with the previously saved application data
   }
   else
   {
      // TODO: Populate the UI with defaults
   }

   EnsurePageCreatedAndActivate();
}

Se il valore di PreviousExecutionState è NotRunning, l'app non è riuscita a salvare correttamente i dati e deve ripartire dallo stato dell'avvio iniziale.If the value of PreviousExecutionState is NotRunning, the app failed to save its application data successfully and the app should start over as if it were being initially launched.

CommentiRemarks

Nota

Le app possono ignorare l'inizializzazione se nella finestra corrente è già presente del contenuto.Apps can skip initialization if there is already content set on the current window. È possibile controllare la proprietà LaunchActivatedEventArgs. TileId per determinare se l'app è stata avviata da un riquadro primario o secondario e, in base a tali informazioni, decidere se è necessario presentare un'esperienza di app aggiornata o ripresa.You can check the LaunchActivatedEventArgs.TileId property to determine whether 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.

API importantiImportant APIs