Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Activities and Their Lifecycle  ›  Lesson

Activity — One Screen, Run by the System

Activity 12 minAn activity is an app component that owns one window of UI; the system creates, shows and destroys it, and your code reacts through callbacks.

Activity — One Screen, Run by the System

Sprout will have a plant list and a plant detail screen. In classic Android each of those screens is an activity. The most important thing to understand about activities is who is in charge of them. It is not you.

The rule

An activity is a screen the system runs; you only answer its calls.

An activity is one of Android's four app components. It owns a window and draws UI into it. Three facts define it:

  1. It is declared in the manifest. If it is not listed, the system refuses to start it.
  2. The system creates it. You never write MainActivity() yourself. You ask the system to start it with an intent, and the system builds the object.
  3. You react through callbacks. The system calls methods such as onCreate, onStart and onResume, and you override them to do your work.
class PlantDetailActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)  // always call super first
        setContent { PlantDetailScreen() }
    }
}

ComponentActivity is the base class used with Compose. Older View-based apps usually extend AppCompatActivity, which is built on top of it.

Modern apps often use one activity and switch between screens with Compose navigation inside it. The activity is still the container the system runs; it just hosts many screens.

The shortcut

Before writing activity code, ask "am I doing this, or is the system?" Creating, showing, hiding and destroying: the system. Filling the screen and reacting: you.

Opening Sprout's detail screenStep 1 of 4
  1. You ask

    Your code calls startActivity(...) with an intent for PlantDetailActivity.

Drills

Answer fast — trust the rule.

quick drill

How should you open a new activity?

quick drill

Which base class is typically used for an activity that shows Compose UI?

quick drill

What must you do in an overridden onCreate before your own code?

quick drill

Which of these is one of Android's four app components?

Remember

  • An activity is a screen the system runs; you only answer its calls.
  • Declared in the manifest, created by the system, driven by callbacks.
  • Never construct an activity or call its lifecycle methods yourself.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWho is in charge?

A teammate writes val screen = PlantDetailActivity() and then screen.onCreate(null) to open Sprout's detail screen. Explain why this is wrong and what they should do instead.