Android官方文档翻译 十七 4.1Starting an Activity

Starting an Activity

开启一个Activity

This lesson teaches you to

这节课教给你

  1. Understand the Lifecycle Callbacks

    理解生命周期回调

  2. Specify Your App’s Launcher Activity

    声明你的App的启动Activity

  3. Create a New Instance

    创建一个新的实例

  4. Destroy the Activity

    销毁Activity

You should also read

你还应该阅读

  • Activities

Unlike other programming paradigms in which apps are launched with a main() method, the Android system initiates code in an Activity instance by invoking specific callback methods that correspond to specific stages of its lifecycle. There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity.

和其他的编程范式:应用程序通过一个main()方法来开启不一样,Android系统通过在一个Activity实例中唤醒与回调方法状态相匹配的指定的回调方法来开始代码的运行。有一系列的回调方法可以开启一个activity,以及一系列的回调方法销毁一个activity。

This lesson provides an overview of the most important lifecycle methods and shows you how to handle the first lifecycle callback that creates a new instance of your activity.

这节课提供了一些最重要的生命周期方法的概述,以及向你展现如何处理第一个生命周期回调:在你的activity中创建一个新的实例。

Understand the Lifecycle Callbacks

理解生命周期回调

During the life of an activity, the system calls a core set of lifecycle methods in a sequence similar to a step pyramid. That is, each stage of the activity lifecycle is a separate step on the pyramid. As the system creates a new activity instance, each callback method moves the activity state one step toward the top. The top of the pyramid is the point at which the activity is running in the foreground and the user can interact with it.

在一个activity的生命中,系统会按顺序调用一系列核心的生命周期方法,就像一个阶梯型金字塔一样。也就是说,activity的生命周期的每种状态都是金字塔中单独的一步。随着系统创建了一个新的activity实例,每个回调方法会把这个activity的状态移向金字塔顶端。金字塔的顶端是正运行在前台的activity,用户可以和它交互。

As the user begins to leave the activity, the system calls other methods that move the activity state back down the pyramid in order to dismantle the activity. In some cases, the activity will move only part way down the pyramid and wait (such as when the user switches to another app), from which point the activity can move back to the top (if the user returns to the activity) and resume where the user left off.

当用户离开这个activity时,系统会调用其他的方法来把这个activity退回到底部以解除这个activity。在某些情况下,activity只有部分会移动到金字塔的底部然后等待(比如当用户选择了另一个应用程序时),在该点activity会返回到金字塔顶部(如果用户要返回该activity时),然后从用户离开的地方重新开始。

Figure 1. A simplified illustration of the Activity lifecycle, expressed as a step pyramid. This shows how, for every callback used to take the activity a step toward the Resumed state at the top, there’s a callback method that takes the activity a step down. The activity can also return to the resumed state from the Paused and Stopped state.

图1。 一个关于Activity生命周期的简化插图,表现为一个阶梯型金字塔。这里展现了对于过去在顶部把activity从顶部移到Resume(继续,也就是运行)状态的每种回调,都有一种回调方法可以让activity返回去。这个activity也可以从Paused(暂停)和Stoped(停止)状态返回到Resumed状态。

Depending on the complexity of your activity, you probably don’t need to implement all the lifecycle methods. However, it’s important that you understand each one and implement those that ensure your app behaves the way users expect. Implementing your activity lifecycle methods properly ensures your app behaves well in several ways, including that it:

你可能不需要完成所有的生命回调方法,这取决于你的activity的复杂度。然而,当你理解了每种状态,然后实现这些方法以确保你的应用程序以用户期待的方式去表现,这是非常重要的。实现你的activity的生命周期方法可以让你的app在某些方面表现的比较好,其中包括:

  • Does not crash if the user receives a phone call or switches to another app while using your app.

    当用户在使用你的应用程序时,如果用户接了一个电话或者选择了另一个应用程序,不会奔溃。

  • Does not consume valuable system resources when the user is not actively using it.

    当用户不主动使用你的应用程序时,不消耗可用的系统资源。

  • Does not lose the user’s progress if they leave your app and return to it at a later time.

    如果用户离开了你的应用程序,然后片刻返回时,不会丢失用户的进程。

  • Does not crash or lose the user’s progress when the screen rotates between landscape and portrait orientation.

    当屏幕在水平方向和竖直方向旋转时,不会崩溃或者不会丢失用户的进程。

As you’ll learn in the following lessons, there are several situations in which an activity transitions between different states that are illustrated in figure 1. However, only three of these states can be static. That is, the activity can exist in one of only three states for an extended period of time:

随着你学习接下来的课程,会有一个activity在不同的状态之间转换的几种情形,也就是图1展现的那样。但是,这些状态中仅仅有三个状态是静态的。也就是说,在较长的一段时间内,activity仅可以以三种状态中的其中一种存在。

  • Resumed

    继续(也就是运行)

    In this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the “running” state.)

    在这种状态中,此activity在前端,用户可以和它进行交互。(有时也被叫作“running”状态)

  • Paused

    暂停

    In this state, the activity is partially obscured by another activity—the other activity that’s in the foreground is semi-transparent or doesn’t cover the entire screen. The paused activity does not receive user input and cannot execute any code.

    在这种状态中,此activity被其它的activity部分掩盖,这个activity以半透明的状态显示在前端,或者没有占用全部屏幕。处于paused状态的activity不能接受用户的输入,也不能执行任何代码。

  • Stopped

    停止

In this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code.

在这种状态下,此activity完全隐藏了,它对于用户是不可见的;它被认为是处于后台。当处于stopped状态时,此activity实例和所有它的状态信息比如成员变量都被保留了,但是它不能运行任何代码。

The other states (Created and Started) are transient and the system quickly moves from them to the next state by calling the next lifecycle callback method. That is, after the system calls onCreate(), it quickly calls onStart(), which is quickly followed by onResume().

其他的状态(创建和开始)是短暂的,系统会通过调用下一个生命周期回调方法从它们迅速移动到下一个状态。也就是说,在系统调用onCreate()方法后,它会迅速地调用onStart()方法,紧接着又会迅速调用onResume()方法。

That’s it for the basic activity lifecycle. Now you’ll start learning about some of the specific lifecycle behaviors.

这就是基本的activity生命周期了。现在你将开始学习关于一些具体的生命周期行为了。

Specify Your App’s Launcher Activity

指定你的应用程序的启动Activity

When the user selects your app icon from the Home screen, the system calls the onCreate() method for the Activity in your app that you’ve declared to be the “launcher” (or “main”) activity. This is the activity that serves as the main entry point to your app’s user interface.

当用户从设备主屏幕上选择了你的app的图标后,系统会调用你的应用程序的Activity中的onCreate()方法,这个Activity你已经声明为“launcher”(或者“main”)activity了。这个activity担任了你的app的用户界面的主启动入口角色。

You can define which activity to use as the main activity in the Android manifest file, AndroidManifest.xml, which is at the root of your project directory.

你可以定义在Android manifest文件下的AndroidManifest.xml中定义使用哪个activity作为主activity。这是你的项目目录的根文件。

The main activity for your app must be declared in the manifest with an that includes the MAIN action and LAUNCHER category. For example:

你的app的主activity必须在manifest中用一个来定义,其中包含MAIN动作和LAUNCHER类别。例如:

<activity android:name=".MainActivity" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Note: When you create a new Android project with the Android SDK tools, the default project files include an Activity class that’s declared in the manifest with this filter.

注意:当你用Android SDK工具创建了一个新的Android项目时,默认的项目文件会包含一个Activity类,它会在在manifest中用这个过滤器进行声明。

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.

如果你的activity没有任何一个声明了MAIN动作或者LAUNCHER类别,那么你的app图标将不会在设备主屏幕的应用程序列表中出现。

Create a New Instance

创建一个新实例

Most apps include several different activities that allow the user to perform different actions. Whether an activity is the main activity that’s created when the user clicks your app icon or a different activity that your app starts in response to a user action, the system creates every new instance of Activity by calling its onCreate() method.

大部分的app会包含几个不同的activity,以允许用户执行不同的动作。无论是当用户点击你的app图标进入的主activity,还是其它的通过用户的动作响应的不同activity,系统都会通过调用activity的onCreate()方法去创建一个新的Activity实例。

You must implement the onCreate() method to perform basic application startup logic that should happen only once for the entire life of the activity. For example, your implementation of onCreate() should define the user interface and possibly instantiate some class-scope variables.

你必须实现onCreate()方法,在此执行基本的应用程序启动逻辑:在activity的整个生命活动中应该只发生一次。例如。在你实现onCreate()方法时应该定义用户界面,有可能还得实例化一些类变量。

For example, the following example of the onCreate() method shows some code that performs some fundamental setup for the activity, such as declaring the user interface (defined in an XML layout file), defining member variables, and configuring some of the UI.

例如,下面这个onCreate()方法的例子中展示了一些代码来运行一些对于activity的基本配置,比如定义了用户界面(在一个XML布局文件中定义),定义了成员变量,以及一些UI的配置。

TextView mTextView; // Member variable for text view in the layout
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Set the user interface layout for this Activity
    // The layout file is defined in the project res/layout/main_activity.xml file
    setContentView(R.layout.main_activity);

    // Initialize member TextView so we can manipulate it later
    mTextView = (TextView) findViewById(R.id.text_message);

    // Make sure we're running on Honeycomb or higher to use ActionBar APIs
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // For the main activity, make sure the app icon in the action bar
        // does not behave as a button
        ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
    }
}

Caution: Using the SDK_INT to prevent older systems from executing new APIs works in this way on Android 2.0 (API level 5) and higher only. Older versions will encounter a runtime exception.

警告:使用SDK_INT来阻止旧系统运行只能在Android 2.0及以上版本才能工作的新的API。旧版本将遇到一个运行时异常。

Once the onCreate() finishes execution, the system calls the onStart() and onResume() methods in quick succession. Your activity never resides in the Created or Started states. Technically, the activity becomes visible to the user when onStart() is called, but onResume() quickly follows and the activity remains in the Resumed state until something occurs to change that, such as when a phone call is received, the user navigates to another activity, or the device screen turns off.

一旦onCreate()结束运行,系统紧接着就会陆续调用onStart()方法和onResume()方法。你的activity从来不会停留在Created或者Started状态下。严格意义上说,当onStart()被调用的时候activity就变得对用户可见了,但是紧接着onResume()会紧跟着运行,activity会保持在Resumed状态,直到一些改变这种状态的现象出现,比如收到了一个电话,用户主动跳转到另一个activity,或者设备的屏幕关闭。

In the other lessons that follow, you’ll see how the other start up methods, onStart() and onResume(), are useful during your activity’s lifecycle when used to resume the activity from the Paused or Stopped states.

在接下来的其他课程中,你将看见在你的activity生命周期期间,当用于从Paused或者Stopped状态恢复activity的时候,其它的启动方式onStart()和onResume()是多么有用。

Note: The onCreate() method includes a parameter called savedInstanceState that’s discussed in the latter lesson about Recreating an Activity.

注意:onCreate()方法包含一个叫做savedInstanceState(保存实例状态)的参数,在以后的关于重新创建一个Activity的课程中我们将会讨论。

Figure 2. Another illustration of the activity lifecycle structre with an emphasis on the three main callbacks that the system calls in sequence when creating a new instance of the activity: onCreate(), onStart(), and onResume(). Once this sequence of callbacks complete, the activity reaches the Resumed state where users can interact with the activity until they switch to a different activity.

图2。 另一个activity生命周期结构的图解,它强调了当创建一个新的activity实例的时候系统依次调用的三个主要回调:onCreate(), onStart(),和 onResume()。一旦这一系列回调完成,系统就会进入Resumed状态,这个状态下,用户就可以和activity进行交互了,直到用户选择进入另一个不同的activity中。

Destroy the Activity

销毁Activity

While the activity’s first lifecycle callback is onCreate(), its very last callback is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.

activity的第一个生命周期回调是onCreate,它的最后一个回调是onDestroy()。系统在你的activity中调用这个方法的最终标志是你的activity实体已经完全从系统内存中移除了。

Most apps don’t need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup during onPause() and onStop(). However, if your activity includes background threads that you created during onCreate() or other long-running resources that could potentially leak memory if not properly closed, you should kill them during onDestroy().

大多数应用程序不需要实现这个方法,因为在onPause()和onStop()中,本地类引用已经随着activity被销毁了,你的activity应该也执行了大部分的清理工作。然而,如果你的activity中包含你在onCreate()中创建的后台线程或者其它的一些可能引起内存泄露的长期运行的资源,这些如果没有被完全关闭,你应该在onDestroy()中杀死它们。

@Override
public void onDestroy() {
    super.onDestroy();  // Always call the superclass

    // Stop method tracing that the activity started during onCreate()
    android.os.Debug.stopMethodTracing();
}

Note: The system calls onDestroy() after it has already called onPause() and onStop() in all situations except one: when you call finish() from within the onCreate() method. In some cases, such as when your activity operates as a temporary decision maker to launch another activity, you might call finish() from within onCreate() to destroy the activity. In this case, the system immediately calls onDestroy() without calling any of the other lifecycle methods.

注意:一般情况下,系统会在它调用onPause()和onStop()之后调用onDestroy(),只有一种情况例外:当你在onCreate()方法中调用finish()方法时。在某些情况下,比如当你的activity作为一个临时的决策者去开启另一个activity时,你可能需要从onCreate()中调用finish()去销毁这个activity。在这种情况下,系统会立即调用onDestroy(),而不会调用其他的任何生命周期方法。

Next: Pausing and Resuming an Activity

下一节:暂停和恢复一个activity

这些是我自己翻译的,如果您发现其中有重要错误,敬请指出,万分感谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值