Understanding Activities

In Android, the building blocks of applications are activities, so before you start banging out bits and bytes, you need a firm understanding of what activities are and how they work. An activity is a single, focused thing a user can do or interact with in an application. For example, when an app presents a list of menu items the user can choose from, that's an activity. When an app displays photographs along with their captions, that's also an activity. An application may consist of just one activity, or like most applications in the Android system, it may contain several. Though activities may work together to appear to be one cohesive application, they are actually independent of each other. An activity in Android is an important part of an application's overall life cycle, and the way the activities are launched and put together is a fundamental part of the Android's application model.

In Android, each activity is implemented as an implementation of the Activity base class. Almost all activities interact with the user, so the Activity class takes care of creating the window for you in which you can place your user interface (UI). Activities are most often presented in full-screen mode, but in some instances, you can find activities floating in windows or embedded inside other activities — this is known as an activity group.

Working with stacks and states

Activities in the system are managed as an activity stack. As users work with a tablet, they move from activity to activity, sometimes across applications. When a new activity is created, it is placed on top of the stack and becomes the running activity. The previous running activity always remains below it in the stack and does not come to the foreground again until the new activity exits.

image I cannot stress enough the importance of understanding how and why the activity works behind the scenes. Not only will you come away with a better understanding of the Android platform, but you will also be able to accurately troubleshoot why your application is doing very odd things at run time.

An activity has essentially four states, as shown in Table 7-1.

Table 7-1 Four Essential States of an Activity

Activity State Description
Active/running The activity is in the foreground of the screen (at the top of the stack).
Paused The activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity). A paused activity is completely alive, meaning that it can completely maintain state and member information and remains attached to the window manager that controls the windows in Android. However, note that the activity can be killed by the Android system in extreme low-memory conditions.
Stopped If an activity becomes completely obscured by another activity, it is stopped. It retains all state and member information, but it is not visible to the user. Therefore, the window is hidden and will often be killed by the Android system when memory is needed elsewhere.
Create and resuming The system has either paused or stopped the activity. The system can either reclaim the memory by asking it to finish or it can kill the process. When it displays that activity to the user, it must resume by restarting and restoring to its previous state.

Tracking an activity's life cycle

Pictures are worth a thousand words, and, in my opinion, flow diagrams are worth ten times that. The following diagram (Figure 7-1) shows the important paths of an activity. This is the activity life cycle.

Figure 7-1: The activity life cycle.

image

The rectangles represent callback methods you can implement to respond to events in the activity. The shaded ovals are the major states that the activity can be in.

Take note of these three loops in your activity:

  • The entire lifetime takes place between the first call to onCreate() and the final call to onDestroy(). The activity performs all the global setup in onCreate() and releases all remaining resources in onDestroy(). For example, if you create a thread to download a file from the Internet in the background, that may be initialized in the onCreate() method. That thread could be stopped in the onDestroy() method.
  • The visible lifetime of the activity takes place between the onStart() and onStop() methods. During this time, the user can see the activity on the screen (though it may not be in the foreground interacting with the user — this can happen when the user is interacting with a dialog box). Between these two methods, you maintain the logic needed to show and run your activity. For example, say that you create an event handler to monitor the state of the phone. When the tablet state changes, this event handler informs the activity that the tablet is, say, going into Airplane mode, so the activity can react accordingly. You would set up the event handler in onStart() and tear down any resources you are accessing in onStop(). The onStart() and onStop() methods can be called multiple times as the activity becomes visible or hidden to the user.
  • The foreground lifetime of the activity begins at the call to onResume() and ends at the call to onPause(). During this time, the activity is in front of all other activities and is interacting with the user. It is normal for an activity to go between onResume() and onPause() multiple times, for example, when the device goes to sleep or when a new activity handles a particular event; therefore, the code in these methods must be fairly lightweight.

The activity life cycle is a large and complex topic. I give you the basics here so that you understand the applications you will be building in this book, but I highly advise that you read through the Activity Life Cycle and Process Life Cycle portions of the Android documentation at http://d.android.com/reference/android/app/Activity.html#ActivityLifecycle and http://d.android.com/reference/android/app/Activity.html#ProcessLifecycle.

image If you are interested in breaking apart your application activities into different manageable chunks, then Fragments may interest you. Fragments were introduced in Android 3.0 to allow you to build more sophisticated and modularized layouts. Fragments are a beast all unto their own and a full discussion of them requires more space than I have in this book. If you are interested, please see the Fragment documentation online at http://d.android.com/guide/topics/fundamentals/fragments.html.

Understanding activity methods

The entire activity life cycle boils down to the following methods. All methods can be overridden, and custom code can be placed in all of them. All activities implement onCreate() for initialization and may also implement onPause() for cleanup. You should always call the superclass (base class) when implementing these methods:

public class Activity extends ApplicationContext {
    protected void onCreate(Bundle savedInstanceState);
    protected void onStart();
    protected void onRestart();
    protected void onResume();
    protected void onPause();
    protected void onStop();
    protected void onDestroy();
}

In general, the movement an activity makes through its life cycle looks like this:

  • onCreate(): Called when the activity is first created. This method is where you initialize your activity and most of your activity's class-wide variables. Most importantly, this is where you tell the activity (using layout resource identifiers) what layout to use. This method is considered the entry point of your activity. Killable: No. Next: onStart().
  • onRestart(): Called after your activity has been stopped prior to being started again. onStart() is always called next. Killable: No. Next: onStart().
  • onStart(): Called when your activity is becoming visible to the user. Followed by onResume() if the activity is brought to the foreground or onStop() if it becomes hidden from the user. Killable: No. Next: onResume() or onStop().
  • onResume(): Called when the activity will be available for interacting with the user. The activity is at the top of the activity stack at this point. Killable: No. Next: onPause().
  • onPause(): Called when the system is about to resume a previous activity or when the user has navigated away to another portion of the system, such as by pressing the home key. Any changes to data made by the user should be committed at this point (that is, if you need to save them). If the activity is brought back to the foreground, onResume() is called; if the activity becomes invisible to the user, onStop() is called. Killable: Yes. Next: onResume() or onStop().
  • onStop(): Called when the activity is no longer visible to the user because another activity has resumed and is covering this one. This may happen because another activity has started or a previous activity has resumed and is now in the foreground of the activity stack. Followed by onRestart() if this activity is coming back to interact with the user or onDestroy() if this activity is going away. Killable: Yes. Next: onRestart() or onDestroy().
  • onDestroy(): The final call you receive before your activity is destroyed. This method gets called either because the activity is finishing (such as someone calling finish() on it or because the system is temporarily destroying the activity to reclaim space). You can distinguish between these two with the isFinishing() method, which helps identify whether the method is actually finishing or the system is killing it. The isFinishing() method is often used inside of onPause() to determine whether the activity is pausing or being destroyed. Killable: Yes. Next: Nothing.

image The methods marked as killable can be “killed” by the Android system at any time without notice. Because of this, you should set up the onPause() method to do any last cleanup and to write any persistent data (such as user edits to data) to your storage mechanism.

Recognizing configuration changes

Configuration changes are important because they can affect an activity's life cycle. A configuration change is defined as a change in screen orientation (the user moving the screen to the side and then back, portrait to landscape and vice versa), language, input devices, and so on. When a configuration change happens, your activity's resources, layout files, and so on might need to change in order to work properly. For example, an application may look completely different if it is interacting with the user in portrait mode as compared to landscape mode (on its side). To deal with this, when a configuration change occurs, your activity is destroyed and goes through the normal activity end-of-life cycle of onPause()imageonStop()imageonDestroy(). After the onDestroy() method is called, the system creates a new instance of the activity, one that uses the new system configuration.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.14.245