Android Lifecycle Triggers, Part 1

This is Part 1 of a multi-part series explaining how events, such as clicking the Home button, trigger transitions in the Android Activity lifecycle. You might want to refer back to this Activity Lifecycle Diagram I posted 20 days ago.

This particular comment inspired me:

I like your diagram, the only thing its missing is what causes each transition to happen (i.e. User hits “back” button, user clicks “home” button etc…)

The activity lifecycle is a complicated state machine which cannot live completely in my head so i like having a diagram to reference, however without the transition events its not a complete reference.

This is indeed complex, and one diagram cannot capture all possible transitions. So I’ll split this up into several blog entries. Here is the first diagram I came up with:

To create this diagram, I wrote an Activity that overrides most of the onXXX() methods, writing log messages:

    @Override
    protected void onDestroy() {
        begin("onDestroy()");
        super.onDestroy();
        end("onDestroy()");
    }
    ...
    private void begin(String signature) {
        // super-hacky code to indent nested method calls
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<indent; i++) {
            sb.append("  ");
        }
        Log.i(TAG, sb.toString() + "BEGIN: " + signature);
        indent++;
    }

    private void end(String signature) {
        indent--;
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<indent; i++) {
            sb.append("  ");
        }
        Log.i(TAG, sb.toString() + "END: " + signature);
    }

I then ran the Activity in Eclipse, viewing the log in the DDMS LogCat window. (NOTE: DDMS is an Eclipse perspective, the LogCat window is in that perspective). I created the diagram using OmniGraffle.

I hope to create additional diagrams showing the sequence of method calls for a variety of events, such as:

  • An incoming phone call
  • The user hits the Menu button
  • Showing a dialog
  • Navigating to a different view
  • The phone going to sleep after inactivity
  • etc…

I suspect that learning the Activity lifecycle is one of the more challenging aspects of Android development. I hope this and future diagrams help.

See Also…


Nils Says:

I suspect that one problem here is that Java (and C# ;-) programmers do not come from a realtime programming background. Consequently, the documentation here is confusing because there is no clear distinction between event, state and action. For example, after looking at the diagram above for a few seconds, it is not obvious how to stop an activity by program code. Should a program ever call an “onMethod()” to initiate some action? That sounds strange.