Activity

01 Jan 2022 . android .

LifeCycle

4 states

  • Running

    Activity is in foreground (on top of the task stack).

  • Paused

    Activity loses focus but still visible to users (covered Activity can be transparent or not completely covered).

  • Stopped

    Activity is invisible and completely covered by another activity.

  • Destroyed

    Activity is finishing or being destroyed by system.

LaunchMode

Task

A collection of activities that users interact with when performing a certain job. The first activity instance is called root of the task.

Back Stack

Activities are arranged with the order in which each activity is opened.

4 launch modes

  • standard

    Default mode. Creates a new instance of an activity in the task from which it was started.

    Example:

    B has “launch mode = standard”.

    • Before launch B A -> B -> C -> D
    • After launch B A -> B -> C -> D -> B
  • singleTop

    If an instance of activity already exists at the top of the current task, a new instance will not be created and Android system will route the intent information through onNewIntent().

    If an instance is not present on top of task then new instance will be created.

    Example:

    D has “launch mode = singleTop”.

    • Before launch D again A -> B -> C -> D
    • After launch D again A -> B -> C -> D (Here old instance gets called and intent data route through onNewIntent() callback)
  • singleTask

    A new task will always be created and a new instance will be pushed to the task as the root one.

    If an instance of activity exists on the separate task, a new instance will not be created and Android system routes the intent information through onNewIntent() method.

    Example:

    B has “launch mode = singleTask”.

    • Before launch B again A -> B -> C -> D
    • After launch B again A -> B (Here old instance gets called and intent data route through onNewIntent() callback)

      Also notice that C and D activities get destroyed here.

  • singleInstance

    It is similar to singleTask except that no other activities will be created in the same task. Any other activity started from here will create in a new task.

    Example:

    D has “launch mode = singleInstance”.

    • Before launch D

      A -> B -> C

    • After launch D

      Task1 — A -> B -> C

      Task2 — D (here D will be in different task)

    • Now if you continue this and start E and D then Stack will look like:

      Task1 — A -> B -> C -> E

      Task2 — D