> For the complete documentation index, see [llms.txt](https://blog.cweihang.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://blog.cweihang.io/android/activity/task-he-hui-tui-zhan.md).

# Task和回退栈

对Task和backStack的认识过程

1.由demo测试得到的关系图：

![task1](/files/-L_G1DZCRKKevdiwnZT9)

* 一个task中可以有多个app的Activity，
* 由于一个app可以对应一个或多个process，
* 所以一个task也可以对应多个process。

**2.由adb shell dumpsys activity测试得到的关系图：** ![task2](/files/-L_G1DZEa_CGdy5oEGfA)

* Android将所有的task维护在Main stack中，
* 每个task由TaskId唯一标识，在Hist中包含了处于同一个task内的Activity，
* 不同的process（拥有不同的PID）中，可以包含同一个app的不同Activity，
* 一个package标识一个Application。

**3.通过学习源码得到的关系图：**&#x20;

![task3](/files/-L_G1DZGzZ1-ocL47DvR)

* 在ActivityManagerService中，由一个ActivityStack对象维护回退栈，而具体到ActivityStack中，由mHistory来维护回退栈（是一个ArrayList，而非Stack）。
* 每个Task即为一个TaskRecord对象，
* TaskRecord没有为每个Task维护一个自己的stack或list，
* mHistory中，不是直接管理Activity，而是维护ActivityRecord对象，
* ActivityRecord对象通过TaskRecord与自己所属的Task关联起来，
* ActivityRecord对象通过Activity info对象与对应的Activity关联起来，
* 分析ActivityStack中的moveTaskToFrontLocked()等对Task进行操作的代码，得到，同一个task的ActivityRecord在mHistory中是放在一起的（按照先入先出的顺序），当一个task被调到前台时，这个mHistory中，属于同一个task（taskId一致）的ActivityRecord被一起移到mHistory的顶端（在这个ArrayList中，以最后一个元素所在的位置为top，top=size()-1）;


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://blog.cweihang.io/android/activity/task-he-hui-tui-zhan.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
