Skip to content

Activities

Activities are the most complex Android components because they are responsible for interacting with the user and with the underlying operating system.

The Android app framework defines an activity lifecycle which provides the developer with the opportunity to execute certain methods at appropriate times. For example, when an app first starts it may need to gather some status information from the local environment before displaying information to the user. Referring to Figure 2, there are three moments where this could be done, onCreate(), onStart() and onResume(). In your code, you would need to declare a method with the appropriate name and the Android framework would automatically run your code at the appropriate time. Methods of this type are called callbacks because they are called from outside your object. The technique relies on the developer using precisely the correct name for the method.

Activity lifecycle Figure 2: Activity lifecycle

As shown in Figure 2, an activity can go through several states, and in most cases, the user can define callbacks to run code as the activity transitions from one state to another.

A lot of default functionality is already provided by a basic Activity class. When you are writing a new activity your declaration should subclass the basic definition and override any of the callback methods you want to use with your own definitions. Figure 3 provides an example. There are also many variations of the basic activity class that you can use.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    public class ExampleActivity extends Activity {
        @Override
        protected void onStart() {
            super.onStart();
            // The activity is about to become visible.
        }
        @Override
        protected void onResume() {
            super.onResume();
            // The activity has become visible (it is now "resumed").
        }
        @Override
        protected void onPause() {
            super.onPause();
            // Another activity is taking focus (this activity is about to be "paused").
        }
        ...

Figure 3: Declaring an activity by subclassing the default class and overriding callback methods

Further reading

Android resources

OO terminology