This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.
配置生命周期监听器
编辑页面
了解允许 Expo Modules API 钩入应用生命周期的机制。
一些 Expo 库需要通过实现 Activity/Application 或 AppDelegate 生命周期回调来处理系统事件,例如深度链接、推送通知和配置更改。
Expo Modules API 提供了一种简单的方法来管理此类回调:
- Android
ApplicationLifecycleDispatcher和ReactActivityHandler会将Application和Activity生命周期事件转发给已注册的监听器。模块可以通过Package类提供ReactActivityLifecycleListener和ApplicationLifecycleListener实现来注册回调。 - iOS
ExpoAppDelegate会将AppDelegate调用转发给已注册的 订阅者。模块可以提供ExpoAppDelegateSubscriber实现来注册 回调。
使用这些机制可以让模块注册行为,而无需你反复编辑原生入口点。
配置你的原生项目
Android
要在 Android 上集成 Application 生命周期监听器,请将你的 Application 类中的 onCreate() 和 onConfigurationChanged() 调用转发给 ApplicationLifecycleDispatcher:
iOS
要在 iOS 上集成 AppDelegate 订阅者,请在你现有的 AppDelegate 实现中将相关调用转发给 ExpoAppDelegateSubscriberManager,以便订阅者能够响应它们:
或者,如果你的 AppDelegate 还没有继承其他类,你可以通过继承 ExpoAppDelegate 来简化设置,它会自动处理转发:
注意: 并非所有可能导致重大副作用的
UIApplicationDelegate方法都受支持。如果你需要依赖某个特定的委托,请查看 Expo 源码(ExpoAppDelegate.swift)以获取完整的转发方法列表。
测试你的集成
要测试回调是否正常工作,请安装一个依赖它们的模块。安装 expo-linking,它使用生命周期监听器来处理深度链接:
- npx expo install expo-linking在代码中为深度链接添加一个监听器,并在打开深度链接时观察控制台:
import * as Linking from 'expo-linking'; import { useEffect } from 'react'; useEffect(() => { const listener = Linking.addEventListener('url', ({ url }) => { console.log('收到深度链接:', url); }); return listener.remove; }, []);
运行以下命令以打开指向你应用的深度链接:
# 如果你在 app.json 中定义了 `android.package` 或 `ios.bundleIdentifier`- npx uri-scheme open com.example.app://somepath/details --android# 如果你在 app.json 中定义了一个 `scheme`- npx uri-scheme open myapp://somepath/details --ios