烂翻译系列之MAUI——应用生命周期

.NET Multi-platform App UI (.NET MAUI) apps generally have four execution states: not runningrunningdeactivated, and stopped. .NET MAUI raises cross-platform lifecycle events on the Window class when an app transitions from the not running state to the running state, the running state to the deactivated state, the deactivated state to the stopped state, the stopped state to the running state, and the stopped state to the not running state.

NET 多平台 App UI (. NET MAUI)应用程序通常有四种执行状态: 非运行、运行、失活和停止。.NET MAUI 在应用程序从非运行状态转换为运行状态、运行状态转换为失活状态、失活状态转换为停止状态、停止状态转换为运行状态、停止状态转换为非运行状态时,会在 Window 类上引发跨平台生命周期事件。

The following diagram shows an overview of the .NET MAUI app lifecycle:

下图显示了.NET MAUI 应用程序生命周期的概述:

 

In the diagram, the gray oval indicates that the app isn't loaded into memory. The light blue ovals indicate that the app is in memory. Text on arcs indicates events that are raised by .NET MAUI, that provide notifications to the running app.

图中,灰色椭圆表示应用程序没有加载到内存中。淡蓝色椭圆表示应用程序在内存中。弧线上的文本表示由.NET MAUI引发的事件,这些事件为正在运行的应用程序提供通知。

The execution state of an app depends on the app's history. For example, when an app is installed for the first time, or a device is started, the app can be considered to be not running. When the app is started, the Created and Activated events are raised and the app is running. If a different app window gains focus, the Deactivated event is raised and the app is deactivated. If the user switches to a different app or returns to the device's Home screen, so that the app window is no longer visible, the Deactivated and Stopped events are raised and the app is stopped. If the user returns to the app, the Resuming event is raised and app is running. Alternatively, an app might be terminated by a user while it's running. In this situation the app is deactivated then stopped, the Destroying event is raised, and the app is not running. Similarly, a device might terminate an app while it's stopped, due to resource restrictions, and the Destroying event is raised and the app is not running.

应用程序的执行状态取决于应用程序的历史记录。例如,当第一次安装应用程序或启动设备时,可以认为该应用程序处于非运行状态。当应用程序启动时,将引发 Created 和 Activated 事件,并且应用程序处于运行状态。如果其他应用程序的窗口获得焦点,Deactivated 事件被引发,应用程序将处于失活状态。 如果用户切换到其他应用或返回到设备的“主屏幕”,使应用窗口不再可见,Deactivated 事件和Stopped 事件被引发,应用程序将处于停止状态。如果用户返回到应用,则会引发Resuming 事件并且应用程序将处于运行状态。或者,应用程序可能在运行时被用户终止。在这种情况下,应用程序先被失活,然后被停止,销毁事件被引发,最终应用程序将处于非运行状态。类似地,由于资源限制,设备可能会在应用程序处于停止状态时终止它,而且会引发 Destroying 事件并且应用程序将处于非运行状态。

In addition, .NET MAUI enables apps to be notified when platform lifecycle events are raised. For more information, see Platform lifecycle events.

此外,.NET MAUI 允许在引发平台生命周期事件时通知应用。 有关详细信息,请参阅 平台生命周期事件

Cross-platform lifecycle events

跨平台生命周期事件

The Window class defines the following cross-platform lifecycle events:

 Window 类定义以下跨平台生命周期事件:

Event  事件Description  描述Action to take  采取的操作
Created 创建 This event is raised after the native window has been created. At this point the cross-platform window will have a native window handler, but the window might not be visible yet.  创建原生窗口后会引发此事件。 此时,跨平台窗口将具有原生窗口处理程序,但该窗口可能尚不可见。  
Activated 激活 This event is raised when the window has been activated, and is, or will become, the focused window.  当窗口已激活并且是或将成为焦点窗口时,将引发此事件。  
Deactivated 失活 This event is raised when the window is no longer the focused window. However, the window might still be visible.  当窗口不再是焦点窗口时,将引发此事件。 但是,该窗口可能仍可见。  
Stopped 停止 This event is raised when the window is no longer visible. There's no guarantee that an app will resume from this state, because it may be terminated by the operating system.  当窗口不再可见时,将引发此事件。 无法保证应用会从此状态恢复,因为它可能被操作系统终止。 Disconnect from any long running processes, or cancel any pending requests that might consume device resources.  断开与任何长时间运行的进程的连接,或取消任何可能消耗设备资源的挂起请求。
Resumed 恢复 This event is raised when an app resumes after being stopped. This event won't be raised the first time your app launches, and can only be raised if the Stopped event has previously been raised.  当应用在停止后恢复时,将引发此事件。 此事件不会在首次启动应用时引发,并且只有在先前已引发停止事件的情况下才能引发。 Subscribe to any required events, and refresh any content that's on the visible page.  订阅任何必需的事件,并刷新可见页面上的任何内容。
Destroying 销毁 This event is raised when the native window is being destroyed and deallocated. The same cross-platform window might be used against a new native window when the app is reopened.  当原生窗口被销毁和释放时,将引发此事件。 重新打开应用时,同样的跨平台窗口可以用于新的原生窗口。 Remove any event subscriptions that you've attached to the native window.  删除附加到原生窗口的所有事件订阅。

These cross-platform events map to different platform events, and the following table shows this mapping:

这些跨平台事件映射到不同平台事件,下表显示了此映射:

Event  跨平台事件Android  安卓事件iOS  iOS事件Windows  Windows事件
Created OnPostCreate FinishedLaunching Created
Activated OnResume OnActivated Activated (CodeActivated and PointerActivated)
Deactivated OnPause OnResignActivation Activated (Deactivated)
Stopped OnStop DidEnterBackground VisibilityChanged
Resumed OnRestart WillEnterForeground Resumed
Destroying OnDestroy WillTerminate Closed

In addition, the Windows class also defines a Backgrounding event that's raised on iOS and Mac Catalyst when the Window is closed or enters a background state.A BackgroundingEventArgs object accompanies this event, and any string state should be persisted to the State property of the BackgroundingEventArgs object, which the OS will preserve until it's time to resume the window. When the window is resumed the state is provided by the IActivationState argument to the CreateWindow override.

此外,Windows 类还定义了当窗口关闭或进入后台状态时,在 iOS 和 Mac Catalyst 上引发的 Background 事件。此事件附带一个 BackoundingEventArgs 对象,并且任何string状态都应该保存到 BackoundingEventArgs 对象的 State 属性中,操作系统将保存该属性,直到恢复窗口为止。 当窗口恢复后,状态由重写的CreateWindow的IActivationState参数提供。

In addition to these events, the Window class also has the following overridable lifecycle methods:

除了这些事件之外,Window 类还有以下可重写的生命周期方法:

  • OnCreated, which is invoked when the Created event is raised.  当引发 Created 事件时调用。
  • OnActivated, which is invoked when the Activated event is raised.  当引发 Activated 事件时调用。
  • OnDeactivated, which is invoked when the Deactivated event is raised.  当引发Deactivated事件时调用。
  • OnStopped, which is invoked when the Stopped event is raised.  当引发Stopped事件时调用。
  • OnResumed, which is invoked when the Resumed event is raised.  当引发Resumed事件时调用。
  • OnDestroying, which is invoked when the Destroying event is raised.  当引发Destroying事件时调用。
  • OnBackgrounding, which is invoked when the Backgrounding event is raised.  当引发Backgrounding事件时调用。

To subscribe to the Window lifecycle events, override the CreateWindow method in your App class to create a Window instance on which you can subscribe to events:

要订阅 Window 生命周期事件,请重写 App 类中的 CreateWindow 方法,以创建一个可以订阅事件的 Window 实例:

 1 namespace MyMauiApp
 2 {
 3     public partial class App : Application
 4     {
 5         public App()
 6         {
 7             InitializeComponent();
 8 
 9             MainPage = new MainPage();
10         }
11 
12         protected override Window CreateWindow(IActivationState activationState)
13         {
14             Window window = base.CreateWindow(activationState);
15 
16             window.Created += (s, e) =>
17             {
18                 // Custom logic
19             };
20 
21             return window;
22         }
23     }
24 }

Alternatively, to consume the lifecycle overrides, create a class that derives from the Window class

或者,要重写生命周期方法,可以创建一个从 Window 类派生的类

 1 namespace MyMauiApp
 2 {
 3     public class MyWindow : Window
 4     {
 5         public MyWindow() : base()
 6         {
 7         }
 8 
 9         public MyWindow(Page page) : base(page)
10         {
11         }
12 
13         protected override void OnCreated()
14         {
15             // Register services
16         }
17     }
18 }

The Window-derived class can then be consumed by overriding the CreateWindow method in your App class to return a MyWindow instance.

然后,可以通过重写 App 类中的 CreateWindow 方法来使用从 Window 派生的类,以返回 MyWindow 实例。


 Warning  警告

An InvalidOperationException will be thrown if the App.MainPage property is set and the CreateWindow method creates a Window object using the override that accepts a Page argument.

如果设置了App.MainPage属性并且CreateWindow方法创建了一个Window对象(使用授受Page参数的重载)。


 

Platform lifecycle events

平台生命周期事件

.NET MAUI defines delegates that are invoked in response to platform lifecycle events being raised. Handlers can be specified for these delegates, using named methods or anonymous functions, which are executed when the delegate is invoked. This mechanism enables apps to be notified when common platform lifecycle events are raised.

.NET MAUI 定义为响应引发的平台生命周期事件而调用的委托。 可以使用命名方法或匿名函数为这些委托指定处理程序,这些函数在调用委托时执行。 此机制使应用能够在引发常见平台生命周期事件时收到通知。


 

 Important  重要

The ConfigureLifecycleEvents method is in the Microsoft.Maui.LifecycleEvents namespace.

ConfigureLificycleEvents 方法位于 Microsoft.Maui.LificycleEvents 命名空间中。


 

Android

安卓

The following table lists the .NET MAUI delegates that are invoked in response to Android lifecycle events being raised:

下表列出了响应引发的 Android 生命周期事件而调用的.NET MAUI 委托:

Delegate  委托Arguments  参数Description  描述Comments  备注
OnActivityResult Android.App.ActivityintAndroid.App.ResultAndroid.Content.Intent? Invoked when an activity you launched exits.  在启动的活动退出时调用。  
OnApplicationConfigurationChanged Android.App.ApplicationAndroid.Content.Res.Configuration Invoked when the device configuration changes while your component is running.  在组件运行时设备配置更改时调用。  
OnApplicationCreate Android.App.Application Invoked when the app has started, before an activity, service, or receiver objects (excluding content providers) have been created.  当应用程序启动后,在活动,服务或接收者对象(不包括内容提供者)创建之前调用。  
OnApplicationCreating Android.App.Application Invoked when the app is starting, before an activity, service, or receiver objects (excluding content providers) have been created.  当应用程序启动时,在活动,服务或接收者对象(不包括内容提供者)创建之前调用。  
OnApplicationLowMemory Android.App.Application Invoked when the system is running low on memory, and actively running processes should trim their memory usage.  当系统内存不足且正在运行的进程应该减少内存使用量时调用。  
OnApplicationTrimMemory Android.App.ApplicationAndroid.Content.TrimMemory Invoked when the operating system has determined that it's a good time for a process to trim unneeded memory from its process.  操作系统已经确定,现在是从进程中删除不需要的内存的好时机时调用。  
OnBackPressed Android.App.Activity Invoked when the activity has detected a press of the back key.  当活动检测到按下back键时调用。  
OnConfigurationChanged Android.App.ActivityAndroid.Content.Res.Configuration Invoked when the device configuration changes while your activity is running.  活动运行时设备配置又发生更改时调用。  
OnCreate Android.App.ActivityAndroid.OS.Bundle? Raised when the activity is created.  创建活动时引发。  
OnDestroy Android.App.Activity Invoked when the activity is finishing, or because the system is temporarily destroying the activity instance to save space.  活动正在完成,或者因为系统正在临时销毁活动实例以节省空间时调用。 Always call the super class's implementation.  始终调用父类的实现。
OnNewIntent Android.App.ActivityAndroid.Content.Intent? Invoked when the activity is relaunched while at the top of the activity stack instead of a new instance of the activity being started.  在活动堆栈顶部重新启动活动时(而不是正在启动的活动的新实例)时调用。  
OnPause Android.App.Activity Invoked when an activity is going into the background, but has not yet been killed.    在活动进入后台但尚未终止时调用。 Always call the super class's implementation.  始终调用父类的实现。
OnPostCreate Android.App.ActivityAndroid.OS.Bundle? Invoked when activity startup is complete, after OnStart and OnRestoreInstanceState have been called.  当活动启动完成后,在调用了OnStart和OnRestoreInstanceState之后调用。 Always call the super class's implementation. This is a system-only event that generally shouldn't be used by apps.  始终调用父类的实现。 这是一个仅限系统的事件,通常不应由应用使用。
OnPostResume Android.App.Activity Invoked when activity resume is complete, after OnResume has been called.  当活动恢复完成后,在调用了OnResume之后调用。 Always call the super class's implementation. This is a system-only event that generally shouldn't be used by apps.  始终调用父类的实现。 这是一个仅限系统的事件,通常不应由应用使用。
OnRequestPermissionsResult Android.App.Activityintstring[]Android.Content.PM.Permission[] Invoked as a callback for the result from requesting permissions.  作为请求权限的结果的回调调用。  
OnRestart Android.App.Activity Invoked after OnStop when the current activity is being redisplayed to the user (the user has navigated back to it).  当前活动正在重新显示给用户(用户已经导航回它)时,在调用了OnStop之后调用。 Always call the super class's implementation.  始终调用父类的实现。
OnRestoreInstanceState Android.App.ActivityAndroid.OS.Bundle Invoked after OnStart when the activity is being reinitialized from a previously saved state.从先前保存的状态重新初始化活动时,在调用了 OnStart 之后调用。  
OnResume Android.App.Activity Invoked after OnRestoreInstanceStateOnRestart, or OnPause, to indicate that the activity is active and is ready to receive input.  在OnRestoreInstanceStateOnRestart, 或 OnPause之后调用,以指示活动处于活动状态并已准备好接收输入。  
OnSaveInstanceState Android.App.ActivityAndroid.OS.Bundle Invoked to retrieve per-instance state from an activity being killed so that the state can be restored in OnCreate or OnRestoreInstanceState.  从正在终止的活动中检索每个实例的状态,以便可以在OnRestoreInstanceState 或 OnCreate 中还原状态。  
OnStart Android.App.Activity Invoked after OnCreate or OnRestart when the activity has been stopped, but is now being displayed to the user.  当活动停止后,但现在正在向用户显示时,在调用了OnCreate或OnRestart之后调用。 Always call the super class's implementation. 始终调用父类的实现。 
OnStop Android.App.Activity Invoked when the activity is no longer visible to the user.  当活动不再对用户可见时调用 Always call the super class's implementation.  始终调用父类的实现。

Important  重要

Each delegate has a corresponding identically named extension method, that can be called to register a handler for the delegate.

每个委托都有相应的同名扩展方法,可以调用该方法为委托注册处理程序。


To respond to an Android lifecycle delegate being invoked, call the ConfigureLifecycleEvents method on the MauiAppBuilder object in the CreateMauiapp method of your MauiProgram class. Then, on the ILifecycleBuilder object, call the AddAndroid method and specify the Action that registers handlers for the required delegates:

若要响应正在调用的 Android 生命周期委托,在 MauiProgram 类的 CreateMauiapp 方法中调用 MauiAppBuilder 对象的 ConfigureLificycleEvents 方法。 然后,在 ILifecycleBuilder 对象上调用 AddAndroid 方法并指定 Action 为所需委托注册处理程序的:

using Microsoft.Maui.LifecycleEvents;

namespace PlatformLifecycleDemo
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureLifecycleEvents(events =>
                {
#if ANDROID
                    events.AddAndroid(android => android
                        .OnActivityResult((activity, requestCode, resultCode, data) => LogEvent(nameof(AndroidLifecycle.OnActivityResult), requestCode.ToString()))
                        .OnStart((activity) => LogEvent(nameof(AndroidLifecycle.OnStart)))
                        .OnCreate((activity, bundle) => LogEvent(nameof(AndroidLifecycle.OnCreate)))
                        .OnBackPressed((activity) => LogEvent(nameof(AndroidLifecycle.OnBackPressed)) && false)
                        .OnStop((activity) => LogEvent(nameof(AndroidLifecycle.OnStop))));
#endif
                    static bool LogEvent(string eventName, string type = null)
                    {
                        System.Diagnostics.Debug.WriteLine($"Lifecycle event: {eventName}{(type == null ? string.Empty : $" ({type})")}");
                        return true;
                    }
                });

            return builder.Build();
        }
    }
}

For more information about the Android app lifecycle, see Understand the Activity Lifecycle on developer.android.com.

有关 Android 应用生命周期的详细信息,请参阅developer.android.com上的 了解活动生命周期 。

iOS

The following table lists the .NET MAUI delegates that are invoked in response to iOS lifecycle events being raised:

下表列出了为响应引发的 iOS 生命周期事件而调用的 .NET MAUI 委托:

Delegate  委托Arguments  参数Description  描述
ApplicationSignificantTimeChange UIKit.UIApplication Invoked when a significant time change occurs, such as midnight, carrier-changed time, or the start or stop of daylight savings.  当一个重要的时间(例如午夜,运营商变更时间,或夏令时的开始或结束)发生变化时调用。
ContinueUserActivity UIKit.UIApplicationFoundation.NSUserActivityUIKit.UIApplicationRestorationHandler Invoked when the app receives data associated with a user activity, such as transferring an activity from a different device using Handoff.  当应用收到与用户活动关联的数据时调用,例如使用 Handoff 从其他设备传输活动。
DidEnterBackground UIKit.UIApplication Invoked when the app has entered the background.  当应用进入后台运行时调用。
FinishedLaunching UIKit.UIApplicationFoundation.NSDictionary Invoked when the app has launched.  在应用启动时调用。
OnActivated UIKit.UIApplication Invoked when the app is launched and every time the app returns to the foreground.  在应用启动时和每次应用返回到前台时调用。
OnResignActivation UIKit.UIApplication Invoked when the app is about to enter the background, be suspended, or when the user receives an interruption such as a phone call or text.  在应用即将进入后台、暂停或用户接到电话或短信等中断时调用。
OpenUrl UIKit.UIApplicationFoundation.NSDictionary Invoked when the app should open a specified URL.  当应用应打开指定的 URL 时调用。
PerformActionForShortcutItem UIKit.UIApplicationUIKit.UIApplicationShortcutItemUIKit.UIOperationHandler Invoked when a Home screen quick action is initiated.  在启动主屏幕快速操作时调用。
SceneContinueUserActivity UIKit.UISceneFoundation.NSUserActivity Invoked to handle the specified Handoff-related activity.  调用以处理指定的与Handoff相关的活动。
SceneDidDisconnect UIKit.UIScene Invoked when a scene is removed from the app.  从应用中删除场景时调用。
SceneDidEnterBackground UIKit.UIScene Invoked when a scene is running in the background and isn't onscreen.  当场景在后台运行且不在屏幕上时调用。
SceneDidFailToContinueUserActivity UIKit.UIScenestringFoundation.NSError Invoked to inform the user that the activity couldn't be completed.  调用以通知用户无法完成活动。
SceneDidUpdateUserActivity UIKit.UISceneFoundation.NSUserActivity Invoked when the specified activity is updated.  在更新指定的活动时调用。
SceneOnActivated UIKit.UIScene Invoked when the scene becomes active and able to respond to user events.  当场景被激活并能够响应用户事件时调用。
SceneOnResignActivation UIKit.UIScene Invoked when the scene is about to resign the active state and stop responding to user events.  当场景即将退出活动状态并停止响应用户事件时调用。
SceneOpenUrl UIKit.UISceneFoundation.NSSet<UIKit.UIOpenUrlContext> Invoked when a scene asks to open one or more URLs.  当场景要求打开一个或多个 URL 时调用。调用 以还原活动状态。
SceneRestoreInteractionState UIKit.UISceneFoundation.NSUserActivity Invoked to restore the activity state.  调用以还原活动状态。
SceneWillConnect UIKit.UISceneUIKit.UISceneSessionUIKit.UISceneConnectionOptions Invoked when a scene is added to the app.  在将场景添加到应用时调用。
SceneWillContinueUserActivity UIKit.UIScenestring Invoked to prepare to receive Handoff-related data.调用以准备接收与 Handoff 相关的数据。
SceneWillEnterForeground UIKit.UIScene Invoked when a scene is about to run in the foreground and become visible to the user.  当场景即将在前台运行并且对用户可见时调用。
WillEnterForeground UIKit.UIApplication Invoked if the app will be returning from a backgrounded state.  如果应用将从后台状态返回,则调用 。
WillFinishLaunching UIKit.UIApplicationFoundation.NSDictionary Invoked when app launching has begun, but state restoration has not yet occurred.  在应用启动已开始,但尚未进行状态还原时调用。
WillTerminate UIKit.UIApplication Invoked if the app is being terminated due to memory constraints, or directly by the user.  如果应用因内存限制而终止,或由用户直接终止,则调用。
WindowSceneDidUpdateCoordinateSpace UIKit.UIWindowSceneUIKit.IUICoordinateSpaceUIKit.UIInterfaceOrientationUIKit.UITraitCollection Invoked when the size, orientation, or traits of a scene change.  当场景的大小、方向或特征发生更改时调用。

Important  重要

Each delegate has a corresponding identically named extension method, that can be called to register a handler for the delegate.

每个委托都有一个相应的同名扩展方法,可以调用该方法来注册委托的处理程序。


To respond to an iOS lifecycle delegate being invoked, call the ConfigureLifecycleEvents method on the MauiAppBuilder object in the CreateMauiapp method of your MauiProgram class. Then, on the ILifecycleBuilder object, call the AddiOS method and specify the Action that registers handlers for the required delegates:

若要响应正在调用的 iOS 生命周期委托,在 MauiProgram 类的 CreateMauiapp 方法中调用 MauiAppBuilder 对象的 ConfigureLificycleEvents 方法。然后,在 ILifecycleBuilder 对象上,调用 AddiOS 方法并指定Action为所需的委托注册处理程序的:

 1 using Microsoft.Maui.LifecycleEvents;
 2 
 3 namespace PlatformLifecycleDemo
 4 {
 5     public static class MauiProgram
 6     {
 7         public static MauiApp CreateMauiApp()
 8         {
 9             var builder = MauiApp.CreateBuilder();
10             builder
11                 .UseMauiApp<App>()
12                 .ConfigureLifecycleEvents(events =>
13                 {
14 #if IOS
15                     events.AddiOS(ios => ios
16                         .OnActivated((app) => LogEvent(nameof(iOSLifecycle.OnActivated)))
17                         .OnResignActivation((app) => LogEvent(nameof(iOSLifecycle.OnResignActivation)))
18                         .DidEnterBackground((app) => LogEvent(nameof(iOSLifecycle.DidEnterBackground)))
19                         .WillTerminate((app) => LogEvent(nameof(iOSLifecycle.WillTerminate))));
20 #endif
21                     static bool LogEvent(string eventName, string type = null)
22                     {
23                         System.Diagnostics.Debug.WriteLine($"Lifecycle event: {eventName}{(type == null ? string.Empty : $" ({type})")}");
24                         return true;
25                     }
26                 });
27 
28             return builder.Build();
29         }
30     }
31 }

For more information about the iOS app lifecycle, see Managing Your App's Life Cycle on developer.apple.com.

关于 iOS 应用程序生命周期的更多信息,请参阅developer.apple.com上的管理应用的生命周期

Windows

The following table lists the .NET MAUI delegates that are invoked in response to Windows lifecycle events being raised:

下表列出了为响应引发的 Windows 生命周期事件而调用的 .NET MAUI 委托:

Delegate  委托Arguments  参数Description  描述
OnActivated Microsoft.UI.Xaml.WindowMicrosoft.UI.Xaml.WindowActivatedEventArgs Invoked when the platform Activated event is raised, if the app isn't resuming.  如果应用程序没有恢复,则在引发平台 Activated 事件时调用。
OnClosed Microsoft.UI.Xaml.WindowMicrosoft.UI.Xaml.WindowEventArgs Invoked when the platform Closed event is raised.  引发平台 Closed 事件时调用。
OnLaunched Microsoft.UI.Xaml.WindowMicrosoft.UI.Xaml.LaunchActivatedEventArgs Invoked by .NET MAUI's Application.OnLaunched override once the native window has been created and activated.  一旦创建并激活了原生窗口,就由.NET MAUI 的 Application.OnLaunched 覆写调用。
OnLaunching Microsoft.UI.Xaml.WindowMicrosoft.UI.Xaml.LaunchActivatedEventArgs Invoked by .NET MAUI's Application.OnLaunched override before the native window has been created and activated.  在原生窗口被创建和激活之前,就由.NET MAUI 的 Application.OnLaunched 覆写调用。
OnPlatformMessage Microsoft.UI.Xaml.WindowWindowsPlatformMessageEventArgs Invoked when .NET MAUI receives specific native Windows messages.  在.NET MAUI 收到特定的原生Windows消息时调用。
OnPlatformWindowSubclassed Microsoft.UI.Xaml.WindowWindowsPlatformWindowSubclassedEventArgs Invoked by .NET MAUI when the Win32 window is subclassed.  在对 Win32 窗口进行子类化时由 .NET MAUI 调用。
OnResumed Microsoft.UI.Xaml.Window Invoked when the platform Activated event is raised, if the app is resuming.  如果应用正在恢复,则在引发平台 Activated 事件时调用。
OnVisibilityChanged Microsoft.UI.Xaml.WindowMicrosoft.UI.Xaml.WindowVisibilityChangedEventArgs Invoked when the platform VisibilityChanged event is raised.  引发平台 VisibilityChanged 事件时调用。
OnWindowCreated Microsoft.UI.Xaml.Window Invoked when the native window is created for the cross-platform Window.  为跨平台窗口创建原生窗口时调用。

.NET MAUI exposes specific native Windows messages as a lifecycle event with the OnPlatformMessage delegate. The WindowsPlatformMessageEventArgs object that accompanies this delegate includes a MessageId property, of type uint. The value of this property can be examined to determine which message has been passed to your app window. For more information about windows messages, see Windows Messages (Get Started with Win32 and C++). For a list of window message constants, see Window notifications.

.NET MAUI 使用 OnPlatformMessage 委托将特定的原生窗口消息公开为生命周期事件。伴随此委托的 WindowsPlatformMessageEventArgs 对象包含一个类型为 uint 的 MessageId 属性。 可以检查此属性的值,以确定哪个消息已传递到应用窗口。 有关 Windows 消息的详细信息,请参阅 Windows 消息 (Win32 和 C++ 入门) 。有关窗口消息常量的列表,请参阅 窗口通知


Important  重要

Each delegate has a corresponding identically named extension method, that can be called to register a handler for the delegate.

每个委托都有一个相应的同名扩展方法,可以调用该方法来注册委托的处理程序。


To respond to a Windows lifecycle delegate being invoked, call the ConfigureLifecycleEvents method on the MauiAppBuilder object in the CreateMauiApp method of your MauiProgram class. Then, on the ILifecycleBuilder object, call the AddWindows method and specify the Action that registers handlers for the required delegates:

若要响应正在调用的 Windows 生命周期委托,在 MauiProgram 类的 CreateMauiApp 方法中调用 MauiAppBuilder 对象的 ConfigureLificycleEvents 方法。然后,在 ILifecycleBuilder 对象上,调用 AddWindows 方法并指定Action为所需委托注册处理程序的 :

 1 using Microsoft.Maui.LifecycleEvents;
 2 
 3 namespace PlatformLifecycleDemo
 4 {
 5     public static class MauiProgram
 6     {
 7         public static MauiApp CreateMauiApp()
 8         {
 9             var builder = MauiApp.CreateBuilder();
10             builder
11                 .UseMauiApp<App>()
12                 .ConfigureLifecycleEvents(events =>
13                 {
14 #if WINDOWS
15                     events.AddWindows(windows => windows
16                            .OnActivated((window, args) => LogEvent(nameof(WindowsLifecycle.OnActivated)))
17                            .OnClosed((window, args) => LogEvent(nameof(WindowsLifecycle.OnClosed)))
18                            .OnLaunched((window, args) => LogEvent(nameof(WindowsLifecycle.OnLaunched)))
19                            .OnLaunching((window, args) => LogEvent(nameof(WindowsLifecycle.OnLaunching)))
20                            .OnVisibilityChanged((window, args) => LogEvent(nameof(WindowsLifecycle.OnVisibilityChanged)))
21                            .OnPlatformMessage((window, args) =>
22                            {
23                                if (args.MessageId == Convert.ToUInt32("031A", 16))
24                                {
25                                    // System theme has changed
26                                }
27                            }));
28 #endif
29                     static bool LogEvent(string eventName, string type = null)
30                     {
31                         System.Diagnostics.Debug.WriteLine($"Lifecycle event: {eventName}{(type == null ? string.Empty : $" ({type})")}");
32                         return true;
33                     }
34                 });
35 
36             return builder.Build();
37         }
38     }
39 }

Retrieve the Window object

检索Window对象

Platform code can retrieve the app's Window object from platform lifecycle events, with the GetWindow extension method:

平台代码可以通过 GetWindow 扩展方法从平台生命周期事件中检索应用程序的 Window 对象:

 1 using Microsoft.Maui.LifecycleEvents;
 2 
 3 namespace PlatformLifecycleDemo
 4 {
 5     public static class MauiProgram
 6     {
 7         public static MauiApp CreateMauiApp()
 8         {
 9             var builder = MauiApp.CreateBuilder();
10             builder
11                 .UseMauiApp<App>()
12                 .ConfigureLifecycleEvents(events =>
13                 {
14 #if WINDOWS
15                     events.AddWindows(windows => windows
16                             .OnClosed((window, args) =>
17                             {
18                                 IWindow appWindow = window.GetWindow();
19                             }));
20 #endif
21                 });
22 
23             return builder.Build();
24         }
25     }
26 }

Custom lifecycle events

自定义生命周期事件

While .NET MAUI defines delegates that are invoked in response to platform lifecycle events being raised, it only exposes a common set of platform lifecycle events. However, it also includes a mechanism, typically for library authors, that enables apps to be notified when additional platform lifecycle events are raised. The process for accomplishing this is as follows:

尽管.NET MAUI定义了在响应平台生命周期事件触发时调用的委托,但它只公开了一组常见的平台生命周期事件。然而,它还包括一种机制,通常是为库作者准备的,可以使应用程序在触发其他平台生命周期事件时得到通知。实现此过程的步骤如下:

  • Register an event handler for a platform lifecycle event that isn't exposed by .NET MAUI.   为未由 .NET MAUI 公开的平台生命周期事件注册事件处理程序。
  • In the event handler for the platform lifecycle event, retrieve the ILifecycleEventService instance and call its InvokeEvents method, specifying the platform event name as its argument.  在平台生命周期事件的事件处理程序中,检索 ILifecycleEventService 实例并调用其 InvokeEvents 方法,并将平台事件名称指定为其参数。

Then, apps that want to receive notification of the platform lifecycle event should modify the CreateMauiApp method of their MauiProgram class to call the ConfigureLifecycleEvents method on the MauiAppBuilder object. Then, on the ILifecycleBuilder object, call the AddEvent method and specify the platform event name and the Action that will be invoked when the platform event is raised.

然后,希望接收平台生命周期事件通知的应用程序应该修改其 MauiProgram 类的 CreateMauiApp 方法,以调用 MauiAppBuilder 对象上的 ConfigureLificycleEvents 方法。然后,在 ILifecycleBuilder 对象上,调用 AddEvent 方法并指定平台事件名称和将在引发平台事件时调用的 Action。

Example

示例

The WinUI 3 Window.SizeChanged event occurs when the native app window has first rendered, or has changed its rendering size. .NET MAUI doesn't expose this platform event as a lifecycle event. However, apps can receive notification when this platform event is raised by using the following approach:

WinUI 3 Window.SizeChanged事件在原生应用程序窗口首次呈现或更改其呈现大小时发生。.NET MAUI 不会将此平台事件公开为生命周期事件。然而,应用程序可以通过以下途径在此平台事件被触发时收到通知:

 1 using Microsoft.Maui.LifecycleEvents;
 2 ...
 3 
 4 public static MauiApp CreateMauiApp()
 5 {
 6       var builder = MauiApp.CreateBuilder();
 7       builder
 8             .UseMauiApp<App>()
 9             .ConfigureLifecycleEvents(events =>
10             {
11 #if WINDOWS
12                   events.AddWindows(windows => windows
13                          .OnWindowCreated(window =>
14                          {
15                                 window.SizeChanged += OnSizeChanged;
16                          }));
17 #endif
18             });
19 
20       return builder.Build();
21 }
  • In the event handler for the platform lifecycle event, retrieve the ILifecycleEventService instance and call its InvokeEvents method, specifying the platform event name as its argument:  在平台生命周期事件的事件处理程序中,检索 ILifecycleEventService 实例并调用其 InvokeEvents 方法,指定平台事件名称作为其参数:
 1 using Microsoft.Maui.LifecycleEvents;
 2 ...
 3 
 4 #if WINDOWS
 5         static void OnSizeChanged(object sender, Microsoft.UI.Xaml.WindowSizeChangedEventArgs args)
 6         {
 7             ILifecycleEventService service = MauiWinUIApplication.Current.Services.GetRequiredService<ILifecycleEventService>();
 8             service.InvokeEvents(nameof(Microsoft.UI.Xaml.Window.SizeChanged));
 9         }
10 #endif

The MauiWinUIApplication type on Windows can be used to access the native app instance via its Current property. The MauiApplication type on Android can be used to access the native app instance. Similarly, the MauiUIApplicationDelegate type on iOS can be used to access the native app instance.  

Windows 上的 MauiWinUIApplication 类型可用于通过其 Current 属性访问原生应用程序实例。Android上的MauiApplication类型可用于访问原生应用程序实例。类似地,iOS 上的 MauiUIApplicationGenerate 类型可用于访问原生应用程序实例。


Warning  警告

Invoking an unregistered event, with the InvokeEvents method, doesn't throw an exception.

使用 InvokeEvents 方法调用未注册的事件不会引发异常。


  • In the CreateMauiApp method of your MauiProgram class, call the ConfigureLifecycleEvents method on the MauiAppBuilder object. Then, on the ILifecycleBuilder object, call the AddEvent method and specify the platform event name and the Action that will be invoked when the platform event is raised:  在 MauiProgram 类的 CreateMauiApp 方法中,调用 MauiAppBuilder 对象的 ConfigureLificycleEvents 方法。然后,在 ILifecycleBuilder 对象上,调用 AddEvent 方法并指定平台事件名称和在引发平台事件时将调用的 Action:
 1 using Microsoft.Maui.LifecycleEvents;
 2 
 3 namespace PlatformLifecycleDemo
 4 {
 5     public static class MauiProgram
 6     {
 7         public static MauiApp CreateMauiApp()
 8         {
 9             var builder = MauiApp.CreateBuilder();
10             builder
11                 .UseMauiApp<App>()
12                 .ConfigureLifecycleEvents(events =>
13                 {
14 #if WINDOWS
15                     events.AddWindows(windows => windows
16                            .OnWindowCreated(window =>
17                            {
18                                   window.SizeChanged += OnSizeChanged;
19                            }));
20 
21                     events.AddEvent(nameof(Microsoft.UI.Xaml.Window.SizeChanged), () => LogEvent("Window SizeChanged"));
22 #endif
23                     static bool LogEvent(string eventName, string type = null)
24                     {
25                         System.Diagnostics.Debug.WriteLine($"Lifecycle event: {eventName}{(type == null ? string.Empty : $" ({type})")}");
26                         return true;
27                     }
28                 });
29 
30             return builder.Build();
31         }
32     }
33 }

The overall effect is that when a user changes the app window size on Windows, the action specified in the AddEvent method is executed.

总体效果是,当用户在 Windows 上更改应用程序窗口大小时,将执行 AddEvent 方法中指定的操作。


Note  注意

The AddEvent method also has an overload that enables a delegate to be specified.

AddEvent 方法还有一个重载,该重载允许指定委托。


 

posted @ 2022-12-18 18:27  菜鸟吊思  阅读(589)  评论(0)    收藏  举报