以下中文是用我自己破爛的英文翻譯,若有翻譯錯誤的地方請多包涵,也歡迎指正。
An
Activity是一種能夠在螢幕上提供與使用者互動的應用程式元件,目的是讓使用者能夠做些事情,例如撥打電話、照相、收發e_mail、瀏覽地圖等。每個activity會給予一個視窗稱作使用者介面(UI),這個視窗可能會填滿整個螢幕,或是比螢幕小,或是重疊於其他視窗上。Activity is an application component that provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows.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" queue mechanism, so, when the user is done with the current activity and presses the BACK key, 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所構成。典型的應用程式會有一個特定的activity稱為main方法,第一次執行程式時會呈現於使用者面前。每個activity可以啟動其他的activity去完成不同的動作。每當開啟一個新的activity時,舊的activity會被停止,但是系統會將此activity保存在back stack之中。一個新的activity會開始作用於back stack之上,並且得到使用者的焦點。back stack遵守著先進先出的序列結構,因此當使用者完成了當前的activity並且按下了BACK鍵,當前的activity會"啪"的被摧毀於stack中,之前的activity將被回復。When an activity is stopped because a new activity starts, it is notified of this change in state through the activity's lifecycle callback methods. There are several callback methods that an activity might receive, due to a change in its state—whether the system is creating it, stopping it, resuming it, or destroying it—and each callback provides you the opportunity to perform specific work that's appropriate to that state change. For instance, when stopped, your activity should release any large objects, such as network or database connections. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted. These state transitions are all part of the activity lifecycle.
經由activity的召回方法(callback methods),會通知這樣的改變狀態:activity會因為新的activity啟動而被停止。不論系統在creating、stopping、resuming或是destroying activity,由於狀態的改變可以讓activity接收不同的召回方法。而且每個召回在狀態的改變下,會提供你更適合完成特定工作的機會。舉例來說,當activity被停止時,會釋放像是網路連結或是資料庫連結的物件。當activity重新運作時,你需要必要的資源和回復動作。這些狀態的傳遞都屬於activity生命週期的一部分。The rest of this document discusses the basics of how to build and use an activity, including a complete discussion of how the activity lifecycle works, so you can properly manage the transition between various activity states.
Creating an Activity
To create an activity, you must create a subclass of
Activity (or an existing subclass of it). In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed. The two most important callback methods are: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 call
setContentView()to define the layout for the activity's user interface. 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).
There are several other lifecycle callback methods that you should use in order to provide a fluid user experience between activities and handle unexpected interuptions that cause your activity to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in the section about Managing the Activity Lifecycle.
Implementing a user interface
The user interface for an activity is provided by a hierarchy of views—objects derived from the
View class. Each view controls a particular rectangular space within the activity's window and can respond to user interaction. For example, a view might be a button that initiates an action when the user touches it.Android provides a number of ready-made views that you can use to design and organize your layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image. "Layouts" are views derived from
ViewGroup that provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout. You can also subclass the View and ViewGroup classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.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 new Views in your activity code and build a view hierarchy by inserting new Views into a ViewGroup, then use that layout by passing the rootViewGroup to setContentView().For information about creating a user interface, see the User Interface documentation.
Declaring the activity in the manifest
You must declare your activity in the manifest file in order for it to be accessible to the system. To decalare your activity, open your manifest file and add an
<activity> element as a child of the <application> element. For example:<manifest ... >
<application ... >
<activity android:name=".ExampleActivity" />
...
</application ... >
...</manifest >There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity's UI. See the
<activity> element reference for more information about available attributes.Using intent filters
An
<activity> element can also specify various intent filters—using the <intent-filter> element—in order to declare how other application components may activate it.When you create a new application using the Android SDK tools, the stub activity that's created for you automatically includes an intent filter that declares the activity responds to the "main" action and should be placed in the "launcher" category. The intent filter looks like this:
<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>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 Filters document.
Starting an Activity
You can start another activity by calling
startActivity(), passing it an Intent that describes the activity you want to start. The intent specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application). An intent can also carry small amounts of data to be used by the activity that is started.When working within your own application, you'll often need to simply launch a known activity. You can do so by creating an intent that explicitly defines the activity you want to start, using the class name. For example, here's how one activity starts another activity named
SignInActivity:Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);However, your application might also want to perform some action, such as send an email, text message, or status update, using data from your activity. In this case, your application might not have its own activities to perform such actions, so you can instead leverage the activities provided by other applications on the device, which can perform the actions for you. This is where intents are really valuable—you can create an intent that describes an action you want to perform and the system launches the appropriate activity from another application. If there are multiple activities that can handle the intent, then the user can select which one to use. For example, if you want to allow the user to send an email message, you can create the following intent:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);The
EXTRA_EMAIL extra added to the intent is a string array of email addresses to which the email should be sent. When an email application responds to this intent, it reads the string array provided in the extra and places them in the "to" field of the email composition form. In this situation, the email application's activity starts and when the user is done, your activity resumes.Starting an activity for a result
Sometimes, you might want to receive a result from the activity that you start. In that case, start the activity by calling
startActivityForResult() (instead ofstartActivity()). To then receive the result from the subsequent activity, implement the onActivityResult() callback method. When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.For example, perhaps you want the user to pick one of their contacts, so your activity can do something with the information in that contact. Here's how you can create such an intent and handle the result:
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...
}
}
}This example shows the basic logic you should use in your
onActivityResult() method in order to handle an activity result. The first condition checks whether the request was successful—if it was, then the resultCode will be RESULT_OK—and whether the request to which this result is responding is known—in this case, the requestCode matches the second parameter sent with startActivityForResult(). From there, the code handles the activity result by querying the data returned in an Intent (the data parameter).What happens is, a
ContentResolver performs a query against a content provider, which returns a Cursor that allows the queried data to be read. For more information, see theContent Providers document.For more information about using intents, see the Intents and Intent Filters document.
Shutting Down an Activity
You can shut down an activity by calling its
finish() method. You can also shut down a separate activity that you previously started by calling finishActivity().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.
0 comments:
Post a Comment