Android 简明教程

Android - Activities

如果你使用过 C、C++ 或 Java 编程语言,那么你一定看到过你的程序从 main() 函数开始。以非常相似的方式,Android 系统在 Activity 中以调用 onCreate() 回调方法开始其程序。有一系列的回调方法可以启动 activity,还有一系列的回调方法可以终止 activity,如下面的 Activity 生命周期图所示: (图像礼貌:android.com )

If you have worked with C, C++ or Java programming language then you must have seen that your program starts from main() function. Very similar way, Android system initiates its program with in an Activity starting with a call on onCreate() callback method. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity as shown in the below Activity life cycle diagram: (image courtesy : android.com )

activity

Activity 类定义了以下回调,即事件。你不必实现所有的回调方法。但是,重要的是你理解每一个方法,并实现那些可以确保你的应用程序按照用户期望的方式运行的方法。

The Activity class defines the following call backs i.e. events. You don’t need to implement all the callbacks methods. However, it’s important that you understand each one and implement those that ensure your app behaves the way users expect.

Sr.No

Callback & Description

1

onCreate() This is the first callback and called when the activity is first created.

2

onStart() This callback is called when the activity becomes visible to the user.

3

onResume() This is called when the user starts interacting with the application.

4

onPause() The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed.

5

onStop() This callback is called when the activity is no longer visible.

6

onDestroy() This callback is called before the activity is destroyed by the system.

7

onRestart() This callback is called when the activity restarts after stopping it.

Example

此示例将引导您完成一些简单步骤以显示 Android 应用程序的生命周期。按照以下步骤修改我们在 Hello World Example 章节中创建的 Android 应用程序 −

This example will take you through simple steps to show Android application activity life cycle. Follow the following steps to modify the Android application we created in Hello World Example chapter −

Step

Description

1

You will use Android studio to create an Android application and name it as HelloWorld under a package com.example.helloworld as explained in the Hello World Example chapter.

2

Modify main activity file MainActivity.java as explained below. Keep rest of the files unchanged.

3

Run the application to launch Android emulator and verify the result of the changes done in the application.

以下是已修改主活动文件 src/com.example.helloworld/MainActivity.java 的内容。该文件包括每个基本生命周期方法。已使用 Log.d() 方法生成日志消息 −

Following is the content of the modified main activity file src/com.example.helloworld/MainActivity.java. This file includes each of the fundamental life cycle methods. The Log.d() method has been used to generate log messages −

package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {
   String msg = "Android : ";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.d(msg, "The onCreate() event");
   }

   /** Called when the activity is about to become visible. */
   @Override
   protected void onStart() {
      super.onStart();
      Log.d(msg, "The onStart() event");
   }

   /** Called when the activity has become visible. */
   @Override
   protected void onResume() {
      super.onResume();
      Log.d(msg, "The onResume() event");
   }

   /** Called when another activity is taking focus. */
   @Override
   protected void onPause() {
      super.onPause();
      Log.d(msg, "The onPause() event");
   }

   /** Called when the activity is no longer visible. */
   @Override
   protected void onStop() {
      super.onStop();
      Log.d(msg, "The onStop() event");
   }

   /** Called just before the activity is destroyed. */
   @Override
   public void onDestroy() {
      super.onDestroy();
      Log.d(msg, "The onDestroy() event");
   }
}

一个活动类使用项目 res/layout 文件夹中可用的 XML 文件加载所有 UI 组件。以下语句从 res/layout/activity_main.xml 文件加载 UI 组件:

An activity class loads all the UI component using the XML file available in res/layout folder of the project. Following statement loads UI components from res/layout/activity_main.xml file:

setContentView(R.layout.activity_main);

一个应用程序可以不受任何限制地拥有一个或多个活动。您为应用程序定义的每个活动都必须在 AndroidManifest.xml 文件中声明,并且应用程序的主活动必须在清单中使用包括 MAIN 操作和 LAUNCHER 类别的 <intent-filter> 声明,如下所示:

An application can have one or more activities without any restrictions. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tutorialspoint7.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

如果为主活动之一未声明 MAIN 操作或 LAUNCHER 类别,那么您的应用程序图标将不会出现在主屏幕的应用程序列表中。

If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen’s list of apps.

让我们尝试运行我们刚刚修改的 Hello World! 应用程序。我假设您在执行环境设置时创建了 AVD 。要从 Android Studio 运行该应用程序,请打开您项目的一个活动文件并单击工具栏中的 Run 图标。Android Studio 将应用程序安装到您的 AVD 并启动它,如果您的设置和应用程序一切正常,它将显示模拟器窗口,并且您应该在 Android Studio 中的 LogCat 窗口中看到以下日志消息 −

Let’s try to run our modified Hello World! application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display Emulator window and you should see following log messages in LogCat window in Android studio −

08-23 10:32:07.682 4480-4480/com.example.helloworld D/Android :: The onCreate() event
08-23 10:32:07.683 4480-4480/com.example.helloworld D/Android :: The onStart() event
08-23 10:32:07.685 4480-4480/com.example.helloworld D/Android :: The onResume() event
android logcat window

让我们尝试单击 Android 模拟器上的锁定屏幕按钮,它将在 Android Studio 中的 LogCat 窗口中生成以下事件消息:

Let us try to click lock screen button on the Android emulator and it will generate following events messages in LogCat window in android studio:

08-23 10:32:53.230 4480-4480/com.example.helloworld D/Android :: The onPause() event
08-23 10:32:53.294 4480-4480/com.example.helloworld D/Android :: The onStop() event

让我们再次尝试解锁 Android 模拟器上的屏幕,它将在 Android Studio 中的 LogCat 窗口中生成以下事件消息:

Let us again try to unlock your screen on the Android emulator and it will generate following events messages in LogCat window in Android studio:

08-23 10:34:41.390 4480-4480/com.example.helloworld D/Android :: The onStart() event
08-23 10:34:41.392 4480-4480/com.example.helloworld D/Android :: The onResume() event

接下来,让我们再尝试单击 Android 模拟器上的后退按钮,它将在 Android Studio 中的 LogCat 窗口中生成以下事件消息,这完成了 Android 应用程序的活动生命周期。

Next, let us again try to click Back button on the Android emulator and it will generate following events messages in LogCat window in Android studio and this completes the Activity Life Cycle for an Android Application.

08-23 10:37:24.806 4480-4480/com.example.helloworld D/Android :: The onPause() event
08-23 10:37:25.668 4480-4480/com.example.helloworld D/Android :: The onStop() event
08-23 10:37:25.669 4480-4480/com.example.helloworld D/Android :: The onDestroy() event