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/ApplicationAppDelegate 生命周期回调来处理系统事件,例如深度链接、推送通知和配置更改。

🌐 Some Expo libraries need to handle system events such as deep links, push notifications, and configuration changes by implementing Activity/Application or AppDelegate lifecycle callbacks.

Expo 模块 API 提供了一种管理此类回调的简便方式:

🌐 The Expo Modules API provides an easy way to manage such callbacks:

  • Android
    ApplicationLifecycleDispatcherReactActivityHandler 会将 ApplicationActivity 生命周期事件转发给已注册的监听器。模块可以通过 Package 类提供 ReactActivityLifecycleListenerApplicationLifecycleListener 实现来注册回调。
  • iOS
    ExpoAppDelegateAppDelegate 调用转发给已注册的订阅者。模块可以提供 ExpoAppDelegateSubscriber 实现来注册回调。

使用这些机制可以让模块注册行为,而无需你反复编辑本地入口点。

🌐 Using these mechanisms allows modules to register behavior without requiring you to edit native entry points repeatedly.

配置你的本地项目

🌐 Configure your native project

安卓

🌐 Android

要在 Android 上集成 Application 生命周期监听器,请将 Application 类中的 onCreate()onConfigurationChanged() 调用转发到 ApplicationLifecycleDispatcher

🌐 To integrate Application lifecycle listeners on Android, forward the onCreate() and onConfigurationChanged() calls from your Application class to ApplicationLifecycleDispatcher:

iOS

To integrate AppDelegate subscribers on iOS, forward the relevant calls to ExpoAppDelegateSubscriberManager in your existing AppDelegate implementation so that subscribers can respond to them:

Alternatively, if your AppDelegate doesn't already extend another class, you can simplify the setup by inheriting from ExpoAppDelegate, which handles the forwarding automatically:

Note: Not all UIApplicationDelegate methods that could cause significant side effects are supported. See the Expo source (ExpoAppDelegate.swift) for the full list of forwarded methods if you need to rely on a specific delegate.

Test your integration

To test if the callbacks are working correctly, install a module that relies on them. Install expo-linking, which uses lifecycle listeners to handle deep links:

Terminal
npx expo install expo-linking

在你的代码中为深度链接添加监听器,并在打开深度链接时观察控制台:

🌐 Add a listener for deep links in your code and observe the console when opening a deep link:

import * as Linking from 'expo-linking'; import { useEffect } from 'react'; useEffect(() => { const listener = Linking.addEventListener('url', ({ url }) => { console.log('Received deep link:', url); }); return listener.remove; }, []);

运行以下命令以打开指向你应用的深度链接:

🌐 Run the following command to open a deep link to your app:

Terminal
# If you have `android.package` or `ios.bundleIdentifier` defined in your app.json
npx uri-scheme open com.example.app://somepath/details --android

# If you have a `scheme` defined in your app.json
npx uri-scheme open myapp://somepath/details --ios