Activity (1)

The Activity class is a crucial component of an Android app, and the way activities are launched and put together is a fundamental part of the platform's application model. Unlike 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.

This document introduces the concept of activities, and then provides some lightweight guidance about how to work with them. For additional information about best practices in architecting your app, see Guide to App Architecture.

---------------------------------------------------------------------------------------------------------------------------------------------------------------

activity是app的一個重要部分,且activity的發佈方式和activity間的結合是平臺中的一個重要部分。不像其他程序是在main()方法中啓動的,android系統通過回調activity生命週期中的一個回調函數來初始化代碼。

這個文檔介紹了activity的概念,提供了一些使用activity的例子。對於如何更好地建設你的app,請參考 guide to app achitecture。

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

concept of activity

The mobile-app experience differs from its desktop counterpart (臺式機) in that a user's interaction with the app doesn't always begin in the same place. Instead, the user journey often begins non-deterministically(不確定的). For instance, if you open an email app from your home screen, you might see a list of emails. By contrast, if you are using a social media app that then launches your email app, you might go directly to the email app's screen for composing an email.

手機app與其臺式機在用戶交互中不同的是,app不總是從相同的地方開始啓動。相反,用戶總是從不確定的地方啓動app。例如,如果你從首頁啓動了一個email app,你也許會看見一個email的列表。相反的,如果你使用社交app來拉起你的email app,你也許會直接到email app的編寫 email 的界面。

The Activity class is designed to facilitate this paradigm. When one app invokes another, the calling app invokes an activity in the other app, rather than the app as an atomic whole. In this way, the activity serves as the entry point for an app's interaction with the user. You implement an activity as a subclass of the Activity class.

activity是爲了使這個過程變得更加靈活而設計的。當一個app調起另一個app,相當於該app調起另一個app的一個activity,而不是這個app作爲一個原子性的整體一樣不可分割。在這個角度看來,acitivity相當於app與用戶的交互入口。你應該通過繼承Activity來實現一個activity。

An activity provides the window in which the app draws its UI. This window typically fills the screen, but may be smaller than the screen and float on top of other windows. Generally, one activity implements one screen in an app. For instance, one of an app’s activities may implement a Preferences screen, while another activity implements a Select Photo screen.

一個activity提供一個app繪製它的UI的窗口。這個窗口一般會充滿屏幕,但也可能比屏幕更小,位於其他window的上面。一般來說,一個acitivity會實現一個app的一個屏幕。例如,一個app的acitvity會實現一個Preference screen,或者另一個activity會實現一個select photo screen。

Most apps contain multiple screens, which means they comprise(包括) multiple activities. Typically, one activity in an app is specified as the main activity, which is the first screen to appear when the user launches the app. Each activity can then start another activity in order to perform different actions. For example, the main activity in a simple e-mail app may provide the screen that shows an e-mail inbox(收件箱). From there, the main activity might launch other activities that provide screens for tasks like writing e-mails and opening individual e-mails.

多數app會包括不同的屏幕,這表示這些app包括多個activity。一般來說,一個app中會有一個activity充當main activity的角色,這個main activity是當用戶打開app時看到的第一個頁面。每一個acitivty可以拉起其他的acitivty去表示不同的意圖。比如說,main activity是一個簡單的email app中的一個展示emai 收件箱的頁面 。從這個頁面,main activity會拉起其他的activity(提供寫email或打開一個單一的email的任務)。

Although activities work together to form a cohesive(拼合的) user experience in an app, each activity is only loosely bound to the other activities; there are usually minimal dependencies among the activities in an app. In fact, activities often start up activities belonging to other apps. For example, a browser app might launch the Share activity of a social-media app.

儘管activity是組合在一起來提供用戶體驗的,每個acitivty與其他的acitivity都是輕耦合的。在app裏面,activity之間總是有少數的依賴。事實上,activity總是拉起其他應用中的activity,例如瀏覽器的app總是拉起社交應用的share activity。

To use activities in your app, you must register information about them in the app’s manifest, and you must manage activity lifecycles appropriately. The rest of this document introduces these subjects.

爲了使用你app中的activity,你必須在app中的manifest中註冊他們的相關信息。且你必須妥善處理activity的生命週期。這個文當的剩下部分將介紹這些部分的信息。

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

For your app to be able to use activities, you must declare the activities, and certain of their attributes, in the manifest.

Declare activities

To declare 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 >

The only required attribute for this element is android:name, which specifies the class name of the activity. You can also add attributes that define activity characteristics such as label, icon, or UI theme. For more information about these and other attributes, see the <activity> element reference documentation.

聲明一個acitivity只需要指明一個屬性,android:name,用來指明activity的類名。你也可以添加一些屬性來定義acitivity的一些特性,比如它的label,icon,或者它的ui主題。想要知道這些的更多信息,可以看activity元素的參考文檔。

Note: After you publish your app, you should not change activity names. If you do, you might break some functionality, such as app shortcuts. For more information on changes to avoid after publishing, see Things That Cannot Change.

Declare intent filters

Intent filters are a very powerful feature of the Android platform. They provide the ability to launch an activity based not only on an explicit request, but also an implicit one. For example, an explicit request might tell the system to “Start the Send Email activity in the Gmail app". By contrast, an implicit request tells the system to “Start a Send Email screen in any activity that can do the job." When the system UI asks a user which app to use in performing a task, that’s an intent filter at work.

intent filter是一個非常有用的功能。他們提供顯式和隱式的兩個方式來拉起另一個activity。比如一個顯式的intent會告訴系統“拉起gmail app中的發送email的acitivity”。相反的,一個隱式的intent會告訴系統 “開啓任意一個可以發送email的activity”。當系統ui詢問用戶想要開啓哪一個app去做這項工作,這就是一個intent filter在工作。

You can take advantage of this feature by declaring an <intent-filter> attribute in the <activity> element. The definition of this element includes an <action> element and, optionally, a <category> element and/or a <data> element. These elements combine to specify the type of intent to which your activity can respond. For example, the following code snippet shows how to configure an activity that sends text data, and receives requests from other activities to do so:

你可以通過在acitivity中聲明Intent-filter來利用這個功能。intent-filter中的聲明包括<action>元素,和可選的<category>,<data>。這些元素聯合在一起去識別你的activity可以響應哪些種類的intent。比如,下面的這些代碼展示怎麼配置一個發送text data的activity,且接收來自其他的activity請求的。

<activity android:name=".ExampleActivity" android:icon="@drawable/app_icon">
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="text/plain" />
    </intent-filter>
</activity>

In this example, the <action> element specifies that this activity sends data. Declaring the <category> element as DEFAULT enables the activity to receive launch requests. The <data> element specifies the type of data that this activity can send. The following code snippet shows how to call the activity described above:

比如:<action>指定了這個activity是發送數據的,聲明<category>元素爲default允許該activity接受其他acitivity的請求,<data>指定activity可以發送的數據類型。下面的code可以展示怎麼調用上面聲明的這個activity。

KOTLINJAVA

// Create the text message with a string
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
// Start the activity
startActivity(sendIntent);

If you intend for your app to be self-contained and not allow other apps to activate its activities, you don't need any other intent filters. 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. For more information about how your activities can respond to intents, see Intents and Intent Filters.

如果你計劃你的app只會自己玩自己的(。。),且不允許別的app調起你的activity,你就不需要任何的intent filter,而使用顯式的intent來開啓其他的activity。

(一篇文章真的好長啊。。。。。,翻譯地我都有點累了。。)

Declare permissions

You can use the manifest's <activity> tag to control which apps can start a particular activity. A parent activity cannot launch a child activity unless both activities have the same permissions in their manifest. If you declare a <uses-permission> element for a parent activity, each child activity must have a matching <uses-permission> element.

你可以使用manifest中的<activity>標籤來控制哪些app可以開啓特定的activity。一個parent activity只能在parent activity和child activity有相同的權限的情況下才能調起child activity。

For example, if your app wants to use a hypothetical app named SocialApp to share a post (發佈帖子)on social media, SocialApp itself must define the permission that an app calling it must have:

比如如果你的app想利用一個叫socialApp來在社交媒體上發佈帖子,SocialApp本身必須定義調用它的應用程序必須具有的權限。

<manifest>
<activity android:name="...."
   android:permission=”com.google.socialapp.permission.SHARE_POST”

/>

(這部分寫在socialApp中)

Then, to be allowed to call SocialApp, your app must match the permission set in SocialApp's manifest:

而爲了你可以調起socialApp,你的app需要擁有socailApp中定義的權限。

<manifest>
   <uses-permission android:name="com.google.socialapp.permission.SHARE_POST" />
</manifest>

(這部分寫在你的app裏)

For more information on permissions and security in general, see Security and Permissions.

(關於更多有關權限與安全的事情,可以查看Security and Permissions)。

Managing the activity lifecycle

Over the course of its lifetime, an activity goes through a number of states. You use a series of callbacks to handle transitions between states. The following sections introduce these callbacks.

在整個activity的生命區間,一個acitivity需要經歷一系列的狀態。你使用一系列的回調函數來處理狀態變換之間的過渡。下面會介紹這些回調函數。

onCreate()

You must implement this callback, which fires when the system creates your activity. Your implementation should initialize the essential components of your activity: For example, your app should create views and bind data to lists here. Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface.

When onCreate() finishes, the next callback is always onStart().

你必須實現這個回調函數,這會在系統創建activity的時候觸發。你應該在這個回調函數裏面初始化activity的相關配置。比如你的app應該在這裏創建view,綁定列表的數據。更重要的是,你需要在這裏調setContentView來定義這個activity使用的佈局。

當onCreate完成後,會調用onStart()

onStart()

As onCreate() exits, the activity enters the Started state, and the activity becomes visible to the user. This callback contains what amounts to the activity’s final preparations for coming to the foreground and becoming interactive.

這個回調函數主要做activity在對用戶可見前的最後準備。

這意味着onStart主管可見性。

onResume()

The system invokes this callback just before the activity starts interacting with the user. At this point, the activity is at the top of the activity stack, and captures all user input. Most of an app’s core functionality is implemented in the onResume() method.

The onPause() callback always follows onResume().

系統在acitivty與用戶可交互之前調用這個回調函數。這時候,actiivty在activity棧中的最頂端,並且獲取用戶的所有輸入。app的主要功能都是在onResume方法中執行。onPause的回調函數總是在onResume()之後。

這意味着,onResume主管可交互。

onPause()

The system calls onPause() when the activity loses focus and enters a Paused state. This state occurs when, for example, the user taps the Back or Recents button. When the system calls onPause() for your activity, it technically means your activity is still partially visible, but most often is an indication that the user is leaving the activity, and the activity will soon enter the Stopped or Resumed state.

系統會在acitivty失去foucus之後,調用onPause進入暫停狀態。這個狀態一般會在用戶點擊返回或最近按鈕的時候出現,這一般意味着你的actiivty仍然處於可視狀態,但會意味着用戶準備離開這個activitry,且該activity很快會進入stopped或resumed狀態。

An activity in the Paused state may continue to update the UI if the user is expecting the UI to update. Examples of such an activity include one showing a navigation map screen or a media player playing. Even if such activities lose focus, the user expects their UI to continue updating.

一個actiivty處於暫停狀態也可能會持續更新它的Ui,如果用戶是希望ui更新的。

You should not use onPause() to save application or user data, make network calls, or execute database transactions. For information about saving data, see Saving and restoring activity state.

你不應該在onPause的時候,保存用戶數據,做網絡請求,或者執行數據庫的交互。對於保存數據,可以看Saving and restoring activity state.

Once onPause() finishes executing, the next callback is either onStop() or onResume(), depending on what happens after the activity enters the Paused state.

一旦onPause執行完成,下一個回調函數就是onStop或onResume,決定於activity在onPause狀態之下發生了什麼。

onStop()

The system calls onStop() when the activity is no longer visible to the user. This may happen because the activity is being destroyed, a new activity is starting, or an existing activity is entering a Resumed state and is covering the stopped activity. In all of these cases, the stopped activity is no longer visible at all. 

系統會在acitivity不再對用戶可見的情況下調用onStop。這會在activity準備被銷燬之前發生,一個新的activity正在新建,或一個已存在的acitivty正在進入onResume狀態,這都將會覆蓋這個處於stopped狀態的activity。在所有的這些情況中,activity都是不再對用戶可見。

The next callback that the system calls is either onRestart(), if the activity is coming back to interact with the user, or by onDestroy() if this activity is completely terminating.

剩下的回調函數系統會調用的是onRestart(),如果這個acitivty將會重新與用戶再次交互,或者

onRestart()

The system invokes this callback when an activity in the Stopped state is about to restart. onRestart() restores the state of the activity from the time that it was stopped.

This callback is always followed by onStart().

onDestroy()

The system invokes this callback before an activity is destroyed.

This callback is the final one that the activity receives. onDestroy() is usually implemented to ensure that all of an activity’s resources are released when the activity, or the process containing it, is destroyed.

This section provides only an introduction to this topic. For a more detailed treatment of the activity lifecycle and its callbacks, see The Activity Lifecycle.

參考鏈接:https://developer.android.com/guide/components/activities/intro-activities#java

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章