阅读:http://developer.android.com/guide/components/activities.html
An application usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in the Tasks and Back Stack document.)
不同Activity的切换依靠back stack,如果有新的Activity出现,新的Activity将入栈。
onCreate()
You must implement this method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly, this is where you must callsetContentView()
to define the layout for the activity's user interface.
在此方法中,必须初始化最基础的组件,但是最重要的是,必须初始化该Activity的layout。
onPause()
The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).
在这个方法中,最重要的就是提交用户的设置。
The most common way to define a layout using views is with an XML layout file saved in your application resources. This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior. You can set the layout as the UI for your activity with
setContentView()
, passing the resource ID for the layout. However, you can also create newView
s in your activity code and build a view hierarchy by inserting newView
s into aViewGroup
, then use that layout by passing the rootViewGroup
tosetContentView()
.
定义一个布局有两种方法:1、一直是脱离代码使用XML文件进行布局;2、往ViewGroup添加Views,然后递交给setContentView()。
The
<action>
element specifies that this is the "main" entry point to the application. The<category>
element specifies that this activity should be listed in the system's application launcher (to allow users to launch this activity).If you intend for your application to be self-contained and not allow other applications to activate its activities, then you don't need any other intent filters. Only one activity should have the "main" action and "launcher" category, as in the previous example. Activities that you don't want to make available to other applications should have no intent filters and you can start them yourself using explicit intents (as discussed in the following section).
However, if you want your activity to respond to implicit intents that are delivered from other applications (and your own), then you must define additional intent filters for your activity. For each type of intent to which you want to respond, you must include an
<intent-filter>
that includes an<action>
element and, optionally, a<category>
element and/or a<data>
element. These elements specify the type of intent to which your activity can respond.For more information about how your activities can respond to intents, see the Intents and Intent Filtersdocument.
<intent-filter>可以让你的Activity被其他程序所调用,如果你不需要这个功能,那么就不需要添加多余的<intent-filter>。
Intent intent = new Intent(this, SignInActivity.class); startActivity(intent);
直接调用当前程序的某Activity。
Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent);
告诉系统你要做什么,并且在intent里添加一些数据。
private void pickContact() { // Create an intent to "pick" a contact, as defined by the content provider URI Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // If the request went well (OK) and the request was PICK_CONTACT_REQUEST if (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) { // Perform a query to the contact's content provider for the contact's name Cursor cursor = getContentResolver().query(data.getData(), new String[] {Contacts.DISPLAY_NAME}, null, null, null); if (cursor.moveToFirst()) { // True if the cursor is not empty int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME); String name = cursor.getString(columnIndex); // Do something with the selected contact's name... } } }
这些代码显示了如何使用startActivityForResult()。
在使用startActivityForResult()的时候需要多一个参数,用于返回成功的基本标识。
还有一个重要的一点就是,需要实现onActivityResult(),在这个方法里有int requestCode, int resultCode, Intent data三个参数,requestCode可用来识别是否成功返回(有可能用户取消选择),resultCode对应startActivityForResult()里的第二个参数,而data则表示返回的数据。
For more information, see the Content Providers document.
For more information about using intents, see the Intents and Intent Filters document.
You can shut down an activity by calling its
finish()
method. You can also shut down a separate activity that you previously started by callingfinishActivity()
.Note: In most cases, you should not explicitly finish an activity using these methods. As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance of the activity.
官方建议不要亲自对Activity使用finish(),而让系统自动管理Activity。
Resumed
The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)
当前状态的Activity意味着它正运行着。
Paused
- Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. A paused activity is completely alive (the
StoppedActivity
object is retained in memory, it maintains all state and member information, and remains attached to the window manager), but can be killed by the system in extremely low memory situations.- The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the
Activity
object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its
finish()
method), or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.
Paused 与 Stopped 的区别在于,Paused还部分可见,而Stopped表示ACtivity已经完全被掩盖了。
但两者拥有许多共同点:1、尽管出在这种状态,但是对象仍然存在于内存中;2、处在这两个状态的Activity都可以被系统finish,如果真的被系统结束了,那么下次打开就需要从头再来了。
public class ExampleActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // The activity is being created. } @Override protected void onStart() { super.onStart(); // The activity is about to become visible. } @Override protected void onResume() { super.onResume(); // The activity has become visible (it is now "resumed"). } @Override protected void onPause() { super.onPause(); // Another activity is taking focus (this activity is about to be "paused"). } @Override protected void onStop() { super.onStop(); // The activity is no longer visible (it is now "stopped") } @Override protected void onDestroy() { super.onDestroy(); // The activity is about to be destroyed. } }
- The entire lifetime of an activity happens between the call to
onCreate()
and the call toonDestroy()
. Your activity should perform setup of "global" state (such as defining layout) inonCreate()
, and release all remaining resources inonDestroy()
. For example, if your activity has a thread running in the background to download data from the network, it might create that thread inonCreate()
and then stop the thread inonDestroy()
.The visible lifetime of an activity happens between the call to
onStart()
and the call toonStop()
. During this time, the user can see the activity on-screen and interact with it. For example,onStop()
is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register aBroadcastReceiver
inonStart()
to monitor changes that impact your UI, and unregister it inonStop()
when the user can no longer see what you are displaying. The system might callonStart()
andonStop()
multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.The foreground lifetime of an activity happens between the call to
onResume()
and the call toonPause()
. During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground—for example,onPause()
is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.
简而言之,onDestroy的时候必须释放所有资源。
程序可见的时间在onStart() and the call to onStop() ,这期间程序都可以被看见,如果有一个在前台很好资源的显示控件,那么应该在onStop的时候暂停它、
程序处于前台的时间再onResume() and the call to onPause().
The column labeled "Killable after?" indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity's code. Three methods are marked "yes": (
onPause()
,onStop()
, andonDestroy()
). BecauseonPause()
is the first of the three, once the activity is created,onPause()
is the last method that's guaranteed to be called before the process canbe killed—if the system must recover memory in an emergency, thenonStop()
andonDestroy()
might not be called. Therefore, you should useonPause()
to write crucial persistent data (such as user edits) to storage. However, you should be selective about what information must be retained duringonPause()
, because any blocking procedures in this method block the transition to the next activity and slow the user experience.Methods that are marked "No" in the Killable column protect the process hosting the activity from being killed from the moment they are called. Thus, an activity is killable from the time
onPause()
returns to the timeonResume()
is called. It will not again be killable untilonPause()
is again called and returns.
onPause是三个有可能被kill掉的最早的状态,因此,最好在这个时刻进行必要数据的存储,避免被系统结束之后失去了重要数据。
onSaveInstanceState()的方法在此时有作用:因为内存紧缺处于暂停或者停止状态的ACtivity被摧毁,但是用户有可能会回来,这个时候有些数据就需要被回复了,系统会在摧毁的时候调用onSaveInstanceState()来存储数据。
该方法的参数是一个Bundle,用键值对来存储数据。而当系统重新建立Activity的时候,存储了数据的Bundle会作为oncreate或者onRestoreInstanceState的参数。
onRestoreInstanceState()与onSaveInstanceState()在父类已经实现,我们可以选择不重写覆盖,但是我们必须为每一个空间增添一个ID作为标志。你也可以选择重写覆盖这两个方法,但是必须先调用父类的实现之后再去做其他的事情。
关于这两个方法最好的例子就是,旋转手机,系统会先摧毁当前的Activity然后重建并且恢复数据。
- Activity A's
onPause()
method executes.- Activity B's
onCreate()
,onStart()
, andonResume()
methods execute in sequence. (Activity B now has user focus.)- Then, if Activity A is no longer visible on screen, its
onStop()
method executes.
这是两个Activity协调的一个例子,总的来说,但启动了另外一个Activity之后,当前ACtivity立即执行onPause(),直到新的Activity获得焦点,老的Activity才进行onStop()。