Middle
What is a Task and in what cases is it used?
sobes.tech AI
Answer from AI
A Task is a unit of work in Android, representing a collection of Activities that are related to each other. Activities within a single Task are arranged in a stack (back stack) in the order they were opened.
Used for:
- Managing the Activity lifecycle: A Task determines the visibility and accessibility of Activities.
- Navigation between applications: When launching an Activity from another app, it is usually placed in its own Task.
- Defining the behavior of the "Back" button: The "Back" button sequentially closes Activities in the current Task.
- Isolation of Activities: Activities from different Tasks do not interact directly by default.
Examples of usage:
- Normal app usage: Opening different screens (Activities) within a single Task.
- Launching a gallery from a messenger: The gallery opens in its own Task, and after selecting an image, it returns to the messenger's Task.
- Handling notifications: Opening an Activity from a notification can create a new Task or use an existing one, depending on the intent flags.
Special behavior of a Task:
- Each Task can have only one root Activity.
- A new Task is created when an Activity is launched with the
FLAG_ACTIVITY_NEW_TASKflag. - An existing Task can be brought to the foreground if an Activity that is already part of it is called with the
FLAG_ACTIVITY_SINGLE_TOPorFLAG_ACTIVITY_CLEAR_TOPflags.
// Example of launching an Activity in a new Task
val intent = Intent(this, NewTaskActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)