处理用户发起的停止正在运行前台服务的应用

从 Android 13(API 级别 33)开始,无论应用的 target SDK 版本为何,用户都可以通过通知抽屉中的工作流来停止正在运行前台服务的应用。此功能称为“任务管理器”,可显示当前正在运行前台服务的应用列表。

At the bottom of the notification drawer is a button that indicates the
    number of apps that are currently running in the background. When you press
    this button, a dialog appears, which lists the names of different apps. The
    Stop button is to the right of each app
图 1. 在运行 Android 13 或更高版本的设备上,任务管理器的工作流。

此列表标有“活跃应用”字样。每个应用旁边都有一个“停止”按钮。图 1 展示了在运行 Android 13 的设备上任务管理器的工作流。

当用户在任务管理器中点按应用旁边的“停止”按钮时,会发生以下操作:

  • 系统会从内存中移除您的应用。因此,您的整个应用都会停止,而不仅仅是正在运行的前台服务。
  • 系统会移除您应用的 Activity 返回栈。
  • 所有媒体播放都会停止。
  • 与前台服务关联的通知会被移除。
  • 您的应用仍保留在历史记录中。
  • 已安排的作业会在其预定时间执行。
  • 闹钟会在其预定时间或时间段内响起。

为了测试在用户停止应用期间和之后您的应用是否按预期运行,请在终端窗口中运行以下 ADB 命令:

adb shell cmd activity stop-app PACKAGE_NAME