您的位置:首页 > 移动开发 > Android开发

Android--Activity简介及生命周期

2015-10-23 09:55 204 查看
1、Activity概述

来自Android
Developers:

An
activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented
to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (usingActivityGroup). There are two methods almost all subclasses of Activity will implement:

*onCreate(Bundle)*
is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

*onPause()*
is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).To
be of use with Context.startActivity(), all activity classes must have a corresponding<activity>
declaration in their package's AndroidManifest.xml.

自己蹩脚的翻译:

Activity
是用户可与之交互的独立的可以聚焦的东西,几乎所有的Activities都是与用户进行交互的,它可以创建提供一个Window,用户可以堆放自己想要的UI效果(用setContentView方法);虽然Activity常常作为全屏的的Window来和用户交互,但它还可以用于以下几种场景,作为浮动的窗口(使用windowIsFloating来装饰activity主题)或者作为另一个activity的一部分(使用ActivityGroup来完成该功能),它的子类大部分都会继承它的以下两个方法:

onCreate(Bundle):当用户初始化activity的地方调用,最重要的是:在这个方法用户通常做法有:用setContentview(int)和layout资源来定制你的UI,在你要用编程的方式进行互动的UI中通过findViewById()获取窗口部件的索引(句柄);

onPause():当用户要离开你的视图的时候,在该方法中来处理你还要做的事情。最重要的是:此时用户所产生的任何的变化(用户数据,activity的数据)都要被记录及提交(常用ContentProvider来保存数据);

为了正常使用Context.startActivity,所有的activity类都要在AndroidManifest.xml中正确的定义及描述。

2、Activity 生命周期

Activities in the system are
managed as an activity stack. When a new activity is started, it is
placed on the top of the stack and becomes the running activity -- the previous activity always remains below it in the stack, and will not come to the foreground again until the new activity exits.

activity在系统中由一个activity栈来管理。当开启一个新的activity,它就放到这个栈的最上层,然后成为运行态的activity-之前的activity在栈中就排布在它下面,并且不会再来到前端直到新的activity存在。

An activity has essentially four states:

If an activity in the foreground of the screen (at the top of the stack), it is active or running.
If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state
and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed
by the system when memory is needed elsewhere.
If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored
to its previous state.

一个activity都拥有4种基本状态:

如果它处于屏幕的最前面,那么它处于活动态或运行态
如果它失去焦点但还是可见(也就是,在你的activity之上存在一个拥有焦点的新的非全屏或透明的activity),它就会pause,一个暂停的activity绝对是“活着的”(它保持所有的状态及信息,并保持和window manager的连接通讯),但是系统处于急需急需内存的极端情况下,它可以被系统“杀”死用于释放内存。
如果它被另一个activity完全覆盖,它就会stop,此时,它始终保持着所有的状态及信息,然而它对用户而言是不可见的,并且当其他应用或地方需要内存时,它就会被“杀”掉。
如果它处于pause或stop状态,系统通过询问关闭它或者直接将它的进程杀掉来关闭该activity;当它再次被用户运行时,它就会完全的从restart开始,来重新来加载它之前的状态。

The following diagram shows the important state paths of an Activity. The square rectangles represent callback methods you can implement to perform operations when
the Activity moves between states. The colored ovals are major states the Activity can be in.

下面的流程图展示了一个activity重要的状态。直角矩形表示这些回调函数,你可以继承并重载这些方法当activity在这些状态间切换的时候;彩色的椭圆表示Activity的主要的状态。



There are three key loops you may be interested in monitoring within your activity:

The entire lifetime of an activity happens between the first call to
onCreate(Bundle)
through
to a single final call to
onDestroy()
. An activity will do all setup of "global"
state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().
The visible lifetime of an activity happens between a call to
onStart()
until
a corresponding call to
onStop()
. During this time the user can see the activity on-screen,
though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a
BroadcastReceiver
in
onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user no longer sees what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
The foreground lifetime of an activity happens between a call to
onResume()
until
a corresponding call to
onPause()
. During this time the activity is in front of all
other activities and interacting with the user. An activity can frequently go between the resumed and paused states -- for example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods
should be fairly lightweight.

在activity中,有3个重要的循环用来监听它的:

完整生命周期:activity完整的一个生命周期是首先调用onCreate()到最后调用onDestroy();activity在onCreate()中进行所有全局状态的初始化及安装,在onDestroy()中释放所有占用的资源;例如:它拥有一个在后台下载数据的一个线程,那么这个线程就会在onCreate()方法中创建,在onDestroy()中停止。
可见的生命周期:activity的可见生命周期就是从调用onStart()直到“适当”的调用onStop方法;在此期间,用户可以在屏幕上看到该activity,尽管它可能不在视图的最前面或者处于用户交互态,在这两个方法之间,你可以持有那些你想要通过activity呈现给用户的资源;例如:你可以在onStart中注册一个广播用于监听UI的变化,然后当用户不再看到你正在展示的东西,就在onStop()中注销这个广播;当activity对用户可见和隐藏两种状态切换时,onStart()和onStop()方法会被多次调用。
处于前置状态的生活周期:它处于首先调用onResume()方法至调用onPause()方法之间,在此期间,它处于所有activity的最前端并且可以和用户交互。activity可以经常在resumed和paused两个状态进行切换,例如:当设备要去睡眠,当一个activity的数据结果要被分发,当一个新的意图要被分发--所以这些方法中的代码要足够的轻量级(否者会产生ANR)。

The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that you can override to do appropriate work when the activity changes state. All activities will implement
onCreate(Bundle)
to
do their initial setup; many will also implement
onPause()
to commit changes to data
and otherwise prepare to stop interacting with the user. You should always call up to your superclass when implementing these methods.
public class Activity extends ApplicationContext {
protected void onCreate(Bundle savedInstanceState);

protected void onStart();

protected void onRestart();

protected void onResume();

protected void onPause();

protected void onStop();

protected void onDestroy();
}


Activity的完整生命周期是由以下的方法来定义的,当activity的状态改变时,你可以重载这些方法进行适当的工作;所有的activity都会继承onCreate()来完成它们初始化的工作,很多也会为了保存改动的数据及暂停与用户交互而去继承onPause()方法,当继承了这些方法,你会经常调用activity的子类。

MethodDescriptionKillable?Next
onCreate()
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
Always followed by
onStart()
.

No
onStart()
onRestart()
Called after your activity has been stopped, prior to it being started again.
Always followed by
onStart()

No
onStart()
onStart()
Called when the activity is becoming visible to the user.
Followed by
onResume()
if the activity comes to the foreground, or
onStop()
if it becomes hidden.
No
onResume()
or
onStop()
onResume()
Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.
Always followed by
onPause()
.
No
onPause()
onPause()
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because
the next activity will not be resumed until this method returns.
Followed by either
onResume()
if the activity returns back to the front, or
onStop()
if it becomes invisible to the user.
Pre-
HONEYCOMB
onResume()
or

onStop()
onStop()
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one
is being destroyed.
Followed by either
onRestart()
if this activity is coming back to interact with the user, or
onDestroy()
if this activity is going away.
Yes
onRestart()
or

onDestroy()
onDestroy()
The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called
finish()
on
it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the
isFinishing()
method.
Yesnothing

Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed
by the system at any time without another line of its code being executed.
Because of this, you should use the
onPause()
method
to write any persistent data (such as user edits) to storage. In addition, the method
onSaveInstanceState(Bundle)
is
called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in
onCreate(Bundle)
if
the activity needs to be re-created. See the Process Lifecycle section
for more information on how the lifecycle of a process is tied to the activities it is hosting. Note that it is important to save persistent data in
onPause()
instead
of
onSaveInstanceState(Bundle)
because
the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

上表中被标记为Killable的列--对那些别标记为killable的方法,处于这些状态的activity可以被kill用于使其他代码的运行,正因为如此,你应该在onPause()方法中进行向存储器中写入任何固定数据,另外,在处于后台状态并即将铺展开的activity之前会调用onSaveInstanceState(Bundle),允许你将要存储到activity的任何动态数据放置到Bundle中,如果这个activity后续要被重新创建,这个Bundle将作为onCreate(Bundle)中的参数;当了解到更多关于进程的生命周期,就会发现使用onPause()方法来存储固定的数据比使用onSaveInstanceState(Bundle)更为重要,因为后者不属于回调生命周期的一部分,所以它不会在任何的状态下被调用,就像它的文件描述一样。

对于那些没有被killable标记的方法,这个activity进程在这些方法调用到方法返回中见都不会被系统kill,一个处于killable状态的activity,一般位于onPause()之后 到 onResume()的开始。

下面通过实例来进行Activity的周期进行学习:

public class MainActivity extends ActionBarActivity {
private static String TAG = "Sunrise";
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG, "onCreate");
}

protected void onStart(){
Log.v(TAG,"onStart");
super.onStart();
}

@Override
protected void onResume() {
Log.v(TAG,"onResume");
super.onResume();
}

@Override
protected void onPause() {
Log.v(TAG,"onPause");
super.onPause();
}

@Override
protected void onStop() {
Log.v(TAG,"onStop");
super.onStop();
}

@Override
protected void onDestroy() {
Log.v(TAG,"onDestory");
super.onDestroy();
}

@Override
protected void onRestart() {
Log.v(TAG,"onRestart");
super.onRestart();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}


启动该应用后,activity的调用情况为:

onCreate()->onStart()->onResume();
后面就主要分为三种情景:
点击手机栏的Back键:
onPause()->onStop()->onDestroy();
此时再进入该应用:
onCreate()->onStart()->onResume();

点击应用的Back键:
onPause()->onStop()->onDestroy();
此时再进入该应用:
onCreate()->onStart()->onResume();

点击home键:
onPause()->onStop();
此时再进入该应用:
onRestart()->onStart()->onResume();

onResume():调用后,就表明activity就是可见的了,可以和用户进行交互的了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: