Android学习路线(十二)Activity生命周期——启动一个Activity

先占个位置,过会儿来翻译,:p

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.

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.

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.

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.

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:

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.

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 callsonStart(),
which is quickly followed by 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 theActivity 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.

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.

The main activity for your app must be declared in the manifest with an <intent-filter> that
includes the MAINaction
and LAUNCHER category.
For example:

<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 anActivity class
that‘s declared in the manifest with this filter.

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.

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.

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.

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.

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.

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.

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.

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

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.

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.

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().

@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
withinonCreate() to
destroy the activity. In this case, the system immediately calls onDestroy() without
calling any of the other lifecycle methods.

Android学习路线(十二)Activity生命周期——启动一个Activity

时间: 2024-10-26 20:46:13

Android学习路线(十二)Activity生命周期——启动一个Activity的相关文章

Android学习路线(二十)运用Fragment构建动态UI

要在Android系统上创建一个动态或者多面板的用户界面,你需要将UI组件以及activity行为封装成模块,让它能够在你的activity中灵活地切换显示与隐藏.你可以使用Fragment类来创建这些模块,它们能够表现得有些像嵌套的activity,它们定义着自己的布局,管理自己的生命周期. 当一个fragment指定了它自己的布局,它可以在activity中和其他的fragment配置为不同的组合,这样就能够为不同的屏幕尺寸来修改你的布局配置(在小屏幕上一次展现一个fragment,而在大屏

Android学习路线(二十四)ActionBar Fragment运用最佳实践

通过前面的几篇博客,大家看到了Google是如何解释action bar和fragment以及推荐的用法.俗话说没有demo的博客不是好博客,下面我会介绍一下action bar和fragment在实战中的应用,以及相关demo源码,希望和大家相互交流. 了解过fragment的同学们应该都知道,fragment是android 3.0版本才出现的的,因此如果要在支持android 3.0一下版本的工程中使用fragment的话是需要添加Support Library的.具体如何添加我就不再赘述

Android学习路线(二十二)运用Fragment构建动态UI——构建一个灵活的UI

先占个位置,下次翻译 :p When designing your application to support a wide range of screen sizes, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space. For example, on a handset devi

Android学习路线(二十一)运用Fragment构建动态UI——创建一个Fragment

你可以把fragment看成是activity的模块化部分,它拥有自己的生命周期,接受它自己的输入事件,你可以在activity运行时添加或者删除它(有点像是一个"子activity",你可以在不同的activity中重用它).本课将向你展示如何使用Support Libaray继承 Fragment 类来让你的应用能够兼容正在运行Android 1.6的设备. 提示: 如果你决定你的应用需求的最低API级别是11或者更高,那么你不需要使用Support Library,你可以直接使用

Android学习路线(二十三)运用Fragment构建动态UI——Fragment间通讯

先占个位置,下次翻译 :p In order to reuse the Fragment UI components, you should build each as a completely self-contained, modular component that defines its own layout and behavior. Once you have defined these reusable Fragments, you can associate them with

Android学习路线(二)创建Android项目

一个Android项目包含了Android app代码在内的所有文件.Android SDK工具提供默认的项目目录和文件让创建一个项目变得很简单. 这篇课程会向大家展示,如何通过Eclipse(包含ADT插件)或者通过在命令行使用SDK工具来创建一个新项目. 提示: 你必须得先安装好Android SDK,如果你使用的是Eclipse,那么你还必须安装了ADT 插件(22.6.2版本或更高).如果你没有这些,可以通过Android SDK安装向导安装好,然后再回到这片课程. 通过Eclipse创

android学习笔记 activity生命周期&amp;任务栈&amp;activity启动模式

activity生命周期 完整生命周期 oncreate->onstart->onresume->onpause->onstop->ondestory 使用场景:应用程序退出自动保存数据 ondestory oncreate 可视生命周期 onstart->onresume->onpause->onstop 使用场景:应用程序最小化 暂停的操作 onstop onstart 前台生命周期 onresume->onpause 界面用户仍然可见,但是失去焦

Android学习笔记十二.深入理解LauncherActvity 之LauncherActivity、PreferenceActivity、PreferenceFragment

深入理解LauncherActvity 之LauncherActivity.PreferenceActivity.PreferenceFragment 从下图我们可以知道,LauncherActivity.PreferanceActivity均继承于ListActivity,其中LauncherActivity实现当列表界面列表项被点击时所对应的Acitvity被启动:PreferanceActivity实现一个程序参数设置.存储功能的Activity列表界面. 一.LauncherActivi

(十二)Maven生命周期和插件

除了坐标.依赖以及仓库之外,Maven的另外两个核心概念是生命周期和插件.在有关Maven的日常使用中,命令行的输入往往就对应了生命周期,如mvn package就表示执行默认生命周期阶段package.Maven的生命周期是抽象的,其实际行为都由插件来完成,如package阶段的任务可能就会由maven-jar-plugin完成.生命周期和插件两者协同工作,密不可分. 1.Maven生命周期 我们在开发项目的时候,我们不断地在经历编译.测试.打包.部署等过程,maven的生命周期就是对所有这些