Android官方入门文档[12]启动一个活动

Android官方入门文档[12]启动一个活动

Starting an Activity
启动一个活动

This lesson teaches you to
1.Understand the Lifecycle Callbacks
2.Specify Your App's Launcher Activity
3.Create a New Instance
4.Destroy the Activity

这节课教你
1.了解生命周期回调
2.指定您的应用程序的启动活动
3.创建一个新实例
4.销毁活动

You should also read
•Activities

你也应该阅读
•活动

Try it out
试试吧

Download the demo
ActivityLifecycle.zip
下载演示
ActivityLifecycle.zip

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系统通过调用对应其生命周期的特定阶段的特定回调方法启动代码的活动实例。还有一个问题就是启动了一个活动,那推倒活动回调方法序列回调方法的序列。

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.
这节课提供的最重要的生命周期方法的概述,并告诉您如何处理的第一个生命周期回调,创建你的活动的一个新实例。

 

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的生命周期的每个阶段是在金字塔的单独步骤。由于该系统创建了一个新的活动实例,每个回调方法移动活动状态一步朝上方。金字塔的顶端是在所述活性在前景中运行的点,并且用户可以与它进行交互。

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)和恢复在用户离开的地方。

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对已恢复状态的步骤在顶部逢回调,有一个回调方法,它的活性下台。活动还可以从暂停和停止状态返回到恢复状态。

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:
•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:
正如你将学到以下课程,有几种情况,其中被如图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.)
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.
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是在前台,并且用户可以与之交互。 (有时也被称为“运行”状态)。
暂停
在这种状态下,activity部分是由另一活动的其它activity这是在前景是半透明或不覆盖整个屏幕遮蔽。暂停活动不接受用户输入并不能执行任何代码。

在这种状态下,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.
这是它的基本活动的生命周期。现在,您将开始学习一些具体的生命周期行为。

 

Specify Your App's Launcher 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.
当用户从主屏幕中的应用程序图标时,系统调用的onCreate()方法的活动在您的应用程序,你已经宣布为“launcher(启动器)”(或“main(主)”)的活动。这是作为主入口点到你的应用程序的用户界面的activity。

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。

The main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category. For example:
为您的应用程序的主要活动必须声明在manifest与意图过滤器<intent-filter>,其中包括MAIN action和LAUNCHER类别。例如:

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类。

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.
如果两个MAIN action 或LAUNCHER类别的活动之一是没有声明,那么你的应用程序图标将不会出现在应用程序的主屏幕上的列表中。

 

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.
大多数应用程序包括几个不同的活动,允许用户执行不同的操作。无论一个活动,当用户点击你的应用程序图标,或者您的应用程序开始响应用户操作的不同activity的创建的主要活动,该系统通过调用其的onCreate()方法创建活动的每一个新的实例。

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()方法来执行应该对活动的整个生命只发生一次基本的应用程序的启动逻辑。例如,你的执行的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()方法的以下示例显示了一些代码,执行一些基本的设置为活动,如宣布的用户界面(在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以防止旧的系统从执行新的API工作在这种方式在Android2.0(API等级5)和更高版本。旧版本会遇到一个运行时异常。

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()方法。你的活动从来没有驻留在创建或启动状态。从技术上来说,活性变得对用户可见时ONSTART()被调用,但onResume()迅速如下,活性保持在续状态,直到东西发生改变的是,当接收到电话呼叫时,例如,用户导航到另一项活动,或设备屏幕关闭。

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.
在接下来的其他课程,你会怎么看其他启动方法,ONSTART()和onResume(),使用时从暂停或停止状态恢复activity是您的活动的生命周期中非常有用。

Note: The onCreate() method includes a parameter called savedInstanceState that's discussed in the latter lesson about Recreating an Activity.
注:的onCreate()方法包括一个名为savedInstanceState参数在有关重新创建的活动,后面的课程进行讨论。

Figure 2. Another illustration of the activity lifecycle structure 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.该活动周期结构的重点是在顺序产生该活动的新实例,当系统调用的三个主要的回调另一个例证:的onCreate(),ONSTART()和onResume()。一旦回调该序列完成后,activity活动达到的续状态,用户可以在与该活动交互,直到它们转换到不同的活动。

 

Destroy the 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.
而活动的第一个生命周期回调的onCreate是(),其最后回调的onDestroy()。系统调用您的活动作为最终信号的活动实例被完全从系统内存中删除此方法。

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()在完成绝大多数的清理。但是,如果你的活动包括您的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.
注:该系统调用的onDestroy()后,它已经称为的onPause()和的onStop()中除一人外的所有情况:当你调用从的onCreate()方法中完成()。在某些情况下,比如当你的活动作为一个临时的决策者推出另一项活动,您可以调用内的onCreate()完成()从破坏该活动。在这种情况下,系统立即调用的onDestroy(),而不调用任何其他生命周期方法。

Next: Pausing and Resuming an Activity
下一页:暂停和恢复的活动

本文翻译自:https://developer.android.com/training/basics/activity-lifecycle/starting.html

时间: 2024-10-26 20:43:29

Android官方入门文档[12]启动一个活动的相关文章

Android官方入门文档[4]启动另一个Activity

Android官方入门文档[4]启动另一个Activity   Starting Another Activity启动另一个Activity This lesson teaches you to1.Respond to the Send Button2.Build an Intent 3.Create the Second Activity4.Receive the Intent5.Display the Message You should also read•Installing the S

Android官方入门文档[1]创建一个Android项目

Android官方入门文档[1]创建一个Android项目   创建一个Android项目   这节课教你1.创建与Android Studio中的一个项目2.创建使用命令行工具项目 你也应该阅读•管理项目 Creating an Android Project This lesson teaches you to1.Create a Project with Android Studio2.Create a Project with Command Line Tools You should

Android官方入门文档[16]创建一个Fragment代码片段

Android官方入门文档[16]创建一个Fragment代码片段   Creating a Fragment创建一个Fragment代码片段   This lesson teaches you to1.Create a Fragment Class2.Add a Fragment to an Activity using XML You should also read•Fragments 这节课教你1.创建一个Fragment代码片段类2.使用XML来添加一个Fragment代码片段给一个活

Android官方入门文档[14]停止和重新启动一个Activity活动

Android官方入门文档[14]停止和重新启动一个Activity活动 Stopping and Restarting an Activity停止和重新启动一个Activity活动   This lesson teaches you to1.Stop Your Activity2.Start/Restart Your Activity You should also read•Activities 这节课教你1.停止您的Activity活动2.启动/重新启动您的Activity活动 你也应该阅

Android官方入门文档[2]运行你的应用程序

Android官方入门文档[2]运行你的应用程序   Running Your App运行你的应用程序   This lesson teaches you to1.Run on a Real Device2.Run on the Emulator You should also read•Using Hardware Devices•Managing AVDs with AVD Manager•Managing Projects 这节课教你1.运行在真实设备2.运行在模拟器 你也应该阅读•使用硬

Android官方入门文档

Android官方入门文档   欢迎来到为Android开发者的培训.在这里,你会发现套课中,描述了如何实现代码示例中的应用程序,你可以重复使用一个特定的任务类.类被组织成可以在左侧导航的顶层看到几个组.这第一组,入门,教你最基本的Android应用程序的开发.如果你是一个新的Android应用程序开发者,你应该按照顺序完成这些课程. 如果你认为你可能更喜欢通过互动视频培训学习的基础知识,看看这个预告片在Android开发的基础的一门课程. Getting Started   Welcome t

Android官方入门文档[7]样式化操作栏

Android官方入门文档[7]样式化操作栏   Styling the Action Bar样式化操作栏   This lesson teaches you to1.Use an Android Theme2.Customize the Background3.Customize the Text Color4.Customize the Tab Indicator You should also read•Styles and Themes•Android Action Bar Style

Android官方入门文档[9]支持不同的语言

Android官方入门文档[9]支持不同的语言 Supporting Different Languages支持不同的语言   This class teaches you to1.Create Locale Directories and String Files2.Use the String Resources You should also read•Localization Checklist•Localization with Resources 该课程教你1.创建区域设置目录和文件

Android官方入门文档[10]支持不同的屏幕

Android官方入门文档[10]支持不同的屏幕   Supporting Different Screens支持不同的屏幕   This lesson teaches you to1.Create Different Layouts2.Create Different Bitmaps You should also read•Designing for Multiple Screens•Providing Resources•Iconography design guide 这节课教你1.创建