Jollen's email: jollen # jollen.org

more: Jollen's Consulting | Jollen's Wiki

« Jollen 的 Android 教學,#10: 如何檢查 Service 是否已啟動?使用 Android 除錯器 | Home | 二零零九年十大 Linux 與 open source 發展預測、Openmoko 新武器 »

Jollen 的 Android 教學,#11: AndroidManifest.xml 的用途是什麼?

jollen 發表於 January 19, 2009 10:39 PM

AndroidManifest.xml 是一個用來描述 Android 應用程式「整體資訊」的設定檔。簡單來說,這是一個「自我介紹」檔,我們可以向 Android 系統「介紹」我們的 Android 應用程式,以便讓 Android 系統完整地了解我們的應用程式資訊。

在 [教學, #9] 中,我們提及:「在這裡修改 AndroidManifest.xml 的目的是為了『在我們的 Android 應用程式裡加入一個 Service 類別』,這樣才有辦法啟動 Service...」這個工作的目的是為了向 Android 系統做二項自我介紹。說明如下。

1. 應用程式「實作了一個 MokoService 類別」

    <application android:icon="@drawable/icon" android:label="@string/app_name">
    ...
        <service android:name=".MokoService">
        ...
        </service>
    ...
    </application>

在 application 標籤裡加入 ‘service’ 標籤,告訴 Android 系統我們的應用程式有一個叫做「MokoService」的類別。「android:name」屬性用來指定 Service 的類別名稱,別忘了在 AndroidManifest.xml 裡,類別名稱都是以「.」(小數點)開始。

2. MokoService 類別可處理「com.moko.hello.START_MUSIC」意圖

       <service android:name=".MokoService">
        	<intent-filter>
        		<action android:name="com.moko.hello.START_MUSIC" />
        		<category android:name="android.intent.category.DEFAULT" />
        	</intent-filter>
        </service>

在 service 標籤裡加入 ‘intent-filter’ 標籤,告訴 Android 系統我們的應用程式可「濾出」哪一個「Intent」。在前面的教學裡,我們把 Intent 暫時解釋為 Event(事件);因此,這裡的「自我介紹」用意是為了告訴 Android 系統,我們可接受的事件名稱為何。

我們只要在 intent-filter 標籤裡加入 ‘action’ 標籤,並指定 action 標籤的 android:name 屬性即可。Intent 的命名規則為「xxx.yyy.NAME」的路徑命名法。

當 Android 收到由 Activity 發出的 Intent 後,便去找尋可處理 com.moko.hello.START_MUSIC 的類別,然後載入並啟動此類別。

最後,在 ’intent-filter’ 裡加入 ‘category’ 標籤,用來定義 com.moko.hello.START_MUSIC 的分類,在這裡指定為預設類別 「android.intent.category.DEFAULT」,這是一個 Android 定義的常數。完整的 Service 類別「自我介紹」標籤與屬性,可參考 Android SDK 的說明。

--jollen

引用通告

如果您想引用這篇文章到您的Blog,
請複製下面的鏈接,並放置到您發表文章的相應界面中。

http://www.jollen.org/cgi-bin/mt3/mt-tb.cgi/605

發表一個評論

(您發表的意見將被立即接受,但需要一點時間與後端伺服器做同步,您的留言才會顯示在網站上。為避免 spam 攻撃,按「發表」後請輸入帳號密碼。使用者帳號:「nospam」、密碼:「nospam」。)

[Top] Copyright (C) 2006,2010 www.jollen.org.
All rights reserved. All content licensed under Creative Commons License.