Android 開發從入門到精通
我們來看看 Android 應用程式的四種主要型別:活動、服務、接收器和 ContentProvider
。我們還要看看顯示使用者介面(UI)元素的檢視。
活動是最常用的 Android 應用程式形式。活動在一個稱為檢視 的類的幫助下,為應用程式提供 UI。檢視類實現各種 UI 元素,比如文字框、標籤、按鈕和計算平臺上常見的其他 UI 元素。
一個應用程式可以包含一個或多個活動。這些活動通常與應用程式中的螢幕形成一對一關係。
應用程式通過呼叫 startActivity()
或 startSubActivity()
方法從一個活動轉移到另一個活動。如果應用程式只需 “切換” 到新的活動,就應該使用前一個方法。如果需要非同步的呼叫/響應模式,就使用後一個方法。在這兩種情況下,都需要通過方法的引數傳遞一個 intent。
由作業系統負責決定哪個活動最適合滿足指定的 intent。
|
與其他多工計算環境一樣,“在後臺” 執行著一些應用程式,它們執行各種任務。Android 把這種應用程式稱為 “服務”。服務是沒有 UI 的 Android 應用程式。
接收器是一個應用程式元件,它接收請求並處理 intent。與服務一樣,接收器在一般情況下也沒有 UI 元素。接收器通常在 AndroidManifest.xml 檔案中註冊。清單 2 是接收器程式碼的示例。注意,接收器的類屬性是負責實現這個接收器的 Java 類。
package com.msi.samplereceiver; import android.content.Context; import android.content.Intent; import android.content.IntentReceiver; public class myreceiver extends IntentReceiver { public void onReceiveIntent(Context arg0, Intent arg1) { // do something when this method is invoked. } } |
|
ContentProvider
是 Android 的資料儲存抽象機制。我們以移動裝置上常見的一種資料為例:地址簿或聯絡人資料庫。地址簿包含所有聯絡人及其電話號碼,使用者在使用手機時可能需要使用這些資料。ContentProvider
對資料儲存的訪問方法進行抽象。ContentProvider
在許多方面起到資料庫伺服器的作用。對資料儲存中資料的讀寫操作應該通過適當的 ContentProvider
傳遞,而不是直接訪問檔案或資料庫。可能還有 ContentProvider
的 “客戶機” 和 “實現”。
下一節介紹 Android 檢視,這是 Android 在移動裝置螢幕上顯示 UI 元素的機制。
|
Android 活動通過檢視顯示 UI 元素。檢視採用以下佈局設計之一:
- LinearVertical
- 後續的每個元素都排在前一個元素下面,形成一個單一列。
- LinearHorizontal
- 後續的每個元素都排在前一個元素右邊,形成一個單一行。
- Relative
- 後續的每個元素相對於前一個元素有一定的偏移量。
- Table
- 與 HTML 表相似的一系列行和列。每個單元格可以包含一個檢視元素。
選擇一種佈局(或佈局的組合)之後,就可以用各個檢視顯示 UI。
檢視元素由大家熟悉的 UI 元素組成,包括:
- Button
- ImageButton
- EditText
- TextView(與標籤相似)
- CheckBox
- Radio Button
- Gallery 和 ImageSwitcher(用來顯示多個影象)
- List
- Grid
- DatePicker
- TimePicker
- Spinner(與組合框相似)
- AutoComplete(具有文字自動補全特性的 EditText)
檢視是在一個 XML 檔案中定義的。清單 3 給出一個簡單的 LinearVertical
佈局示例。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Activity 1!" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Activity 1, second text view!" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch To Activity 2" id="@+id/switchto2" /> </LinearLayout> |
注意,每個元素有一個或多個屬於 Android 名稱空間的屬性。
下一節討論如何獲取 Android SDK 並在 Eclipse 環境中配置它。