> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kontext.so/llms.txt
> Use this file to discover all available pages before exploring further.

# 跟随页面的生命周期

> 谁持有该集的 VideoAds，何时销毁它：Activity、Fragment、ViewModel 或 Compose。

`VideoAds` 属于观众正在观看的这一集：页面打开时创建它，并由持有它的一方 `destroy()` 它。

* 由 `ViewModel` 持有：在 `onCleared()` 中调用 `destroy()`，并在每个新的 Activity 中对它的播放器调用 `track`。广告在旋转时保留，屏幕上的广告也是，它比 Activity 活得更久：从当前页面设置它的监听器，每次重建后重新设置，并在 `onDestroy()` 中清除，这样 `onAdEnded` 永远不会送达已销毁的 Activity（旧页面留下的监听器也会让旧页面一直可达）。

  ```kotlin theme={null}
  override fun onCreate(savedInstanceState: Bundle?) {
      // …
      model.ads.track(player)
      model.pauseAd?.listener = this         // 由这个页面接收广告的结束
  }

  override fun onDestroy() {
      super.onDestroy()
      model.pauseAd?.listener = null         // 绝不送达已销毁的 Activity
  }
  ```
* 由 Activity、Fragment 或 Compose 的 `DisposableEffect` 持有：在它的 `onDestroy()`（`onDispose`）中调用 `destroy()`，每次都调用。旋转或其他配置变更会销毁并重建 Activity，广告也随之销毁：像示例应用一样为旋转声明 `android:configChanges`，让旋转不会重建它。
* 被持有者遗忘的 `VideoAds` 永远不会被释放：它持有自己的播放器适配器、广告和它们的监听器。
* 线性广告在 SDK 自己的 Activity 中运行，覆盖在你的 Activity 之上。你的 Activity 在此期间被停止，并可能被销毁和重建（旋转、系统回收内存）；`VideoAds` 放在 `ViewModel` 中时，或者对于旋转、放在声明了 `android:configChanges` 的 Activity 中时，广告会继续播放，它的结束会送达展示它时的监听器。
* 线性广告不支持 `launchMode="singleInstance"` 的播放器 Activity：广告会在另一个任务中打开，观众会回到那个任务。请使用 `standard`、`singleTop` 或 `singleTask`。
* [示例应用](https://docs.kontext.so/zh/video/sdk/kotlin/example.md)用 `android:configChanges` 让播放器 Activity 在旋转时保留，并在每个 `onDestroy()` 中调用 `ads.destroy()`。
* 广告持有它的监听器直到 `onAdEnded` 运行完毕，所以作为监听器的 Activity 在广告结束前一直可达。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.