Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
1000 / James Steele, Nelson To - The Android Developer’s Cookbook Building Applications with the Android SDK - 2010.pdf
3.58 Mб

30 Chapter 2 Application Basics: Activities and Intents

does not support the required features in the application. Always choose the lowest API level possible when specifying this.

The AndroidManifest can also contain permission settings needed to run the application. More complete details about the options are provided in later chapters, but this suffices to cover the recipes in this chapter.

Renaming Parts of an Application

Sometimes a portion of an Android project needs to be renamed. Maybe a file was copied manually into the project, such as from this book. Maybe the application name has changed during development, and it needs to be reflected in the filesystem tree. Automatic tools help with this and ensure cross-referencesare automatically updated. For example, in the Eclipse IDE, the different ways to rename portions of an application are

nRename the Android project, as follows:

1.Right-clickthe project andRefactor Move to a new directory in the filesystem.

2.Right-clickthe project andRefactor Rename the project.

nRename an Android package, as follows:

1.Right-clickthe package andRefactor Rename the package.

2.Edit the AndroidManifest.xml to ensure the new package name is reflected.

nRename an Android class (such as the major components Activity,Service,

BroadcastReceiver, ContentProvider), as follows:

1.Right-clickthe.java file andRefactor Rename the class.

2.Edit the AndroidManifest.xml to ensure theandroid:name has the new component name.

Note that renaming other files, such as XML files, usually requires manually changing the corresponding references in the Java code.

Activity Lifecycle

Each activity in an application goes through its own lifecycle. Once and only once when an activity is created, is the onCreate() function executed. If the activity exits, theonDestroy() function is executed. In between, various events can lead to the activity being in multiple different states, as illustrated in Figure 2.2.The next recipe provides an example of each of these functions.

Download at www.wowebook.com

Activity Lifecycle











User navigates



back to the activity




Process is








Activity is

The activity comes



to the foreground


Another activity comes



in front of the activity




The activity comes

Other applications


to the foreground



need memory





The activity is no



longer visible








Activity is shut down

Figure 2.2 Activity Lifecycle fromhttp://developer.android.com/.

Recipe: Utilizing Other Lifecycle Functions

The following recipe provides a simple way to see the activity lifecycle in action. For illustration purposes, each overridden function is explicit and a Toast command is added to show on screen when the function is entered (more detail on the Toast widget is

Download at www.wowebook.com

32 Chapter 2 Application Basics: Activities and Intents

provided in Chapter 3).The activity is shown in Listing 2.6. Run it on an Android device and try various cases. In particular, note the following:

nChanging the screen orientation destroys and recreates the activity from scratch.

nPressing the Home button pauses the activity, but does not destroy it.

nPressing the Application icon might start a new instance of the activity, even if the old one was not destroyed.

nLetting the screen sleep pauses the activity and the screen awakening resumes it. (This is similar to taking an incoming phone call.)

Listing 2.6 src/com/cookbook/activity_lifecycle/ActivityLifecycle.java

package com.cookbook.activity_lifecycle;

import android.app.Activity; import android.os.Bundle; import android.widget.Toast;

public class ActivityLifecycle extends Activity {


public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();



protected void onStart() { super.onStart();

Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();



protected void onResume() { super.onResume();

Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();



protected void onRestart() { super.onRestart();

Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT).show();


Download at www.wowebook.com

Activity Lifecycle



protected void onPause() {

Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show(); super.onPause();



protected void onStop() {

Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show(); super.onStop();



protected void onDestroy() {

Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show(); super.onDestroy();



As seen here, various common actions by the user can cause the activity to be paused, killed, or even launch multiple versions of the application. Before moving on, it is worth mentioning two additional simple recipes that can control this behavior.

Recipe: Forcing Single Task Mode

As an application is navigated away from and launched again, it can lead to multiple instances of the activity on the device. Eventually the redundant instance of the activity is killed to free up memory, but in the meantime, it can lead to odd situations.To avoid these, the developer can control this behavior for each activity in the AndroidManifest.

To ensure only one instance of the activity runs on the device, specify the following in an activity element that has theMAIN andLAUNCHER intent filters:


This keeps a single instance of each activity in a task at all times. In addition, any child activity is launched as its own task.To constrain even further to only have a single task for all activities of an application, use the following:


This allows the activities to share information easily as the same task.

In addition, it might be desirable to retain the task state, regardless of how a user navigates to the activity. For example, if a user leaves the application and relaunches it later, the default behavior often resets the task to its initial state.To ensure the user always

Download at www.wowebook.com

Соседние файлы в папке 1000


Сервис бесплатной оценки стоимости работы

  1. Заполните заявку. Специалисты рассчитают стоимость вашей работы
  2. Расчет стоимости придет на почту и по СМС

Нажимая на кнопку, вы соглашаетесь с политикой конфиденциальности и на обработку персональных данных.

Номер вашей заявки

Прямо сейчас на почту придет автоматическое письмо-подтверждение с информацией о заявке.

Оформить еще одну заявку