[Android] Application Fundamentals - Application Components

Android的application通常由以下四個元素所組成,但並不是絕對需要。
  • Activity
  • Intent Receiver
  • Service
  • Content Provider

當我們確定哪些元素後,我們就需要在AndroidManifest.xml中登記這些構造塊的清單。這個配置文件用於定義應用程序的組件、組件的功能及必要條件等。

以下,我們對四種元素的說明:

Activity

Activity是一個虛擬的UI(User Interface),並且繼承於Activity這個class。一個activity可以啟動新的activity,原來的activity會pause,系統會將它放進history stack,也可以移除,而新產生的activity可以傳直給原來的activity。

Service

沒有UI的程式,activity使用Context.startService()將service啟動,再使用Context.bindService()來跟service做連結,之後則使用service開放出來的介面做溝通。

Broadcast receivers

想發送一個廣播事件可以使用BroadcastReceiver class,broadcast receiver沒有UI,使用NotificationManager來通知使用者,通知的方法有閃背光、震動、聲音等等。它通常會顯示在status bar。

Content Provider

應用程式可以分享資料給其它的應用程式,並且將它們的資料保存到檔案、SQLite database,甚至是其它機制。而ContentResolver這個物件可以與任何的content provider溝通。


  • Activating components: intents

一個特別的類別intent,當content provider被ContentResolver觸發時,activities、service、與broadcast receivers會被非同步的訊息觸發,而這個觸發稱為intent。Intent負責傳遞資料。分為以下三種類型:

Activity啟動是用intent傳遞Context.startActivity() or Activity.startActivityForResult()。

Service啟動是用intent傳遞Context.startService()。

應用程式使用廣播是用intent傳遞Context.sendBroadcast()。

  • Shutting down components

關掉acticity可以使用finish()。一個activity可以關掉另一個activity,使用finishActivity(),而activity由startActivityForResult()所啟動。

關掉service則使用stopSelf()或Context.stopService()。

The manifest file

Application component會在一個manifest的檔案裡,並且組合在Android package(.apk),.apk檔裡包含應用程式的code, file, 和 resource。

一個Android application component需要有AndroidManifest.xml檔案,你必需宣告你要使用的元件並指出它們所擁有的能力及需求。

以下是個例子:

<?xml version="1.0" encoding="utf-8"?>
<manifest . . . >
<application . . . >
<activity android:name="com.example.project.FreneticActivity"
android:icon="@drawable/small_pic.png"
android:label="@string/freneticLabel"
. . . >
</activity>
. . .
</application>
</manifest>

可以在的位置加上<service>,<receiver>, and <provider>。

  • Intent filters
當Intent要求做某些事情時,IntentFilter被用來描述這個activity能夠做些什麼事情。IntentFilter會宣告在AndroidManifest.xml檔案裏。

以下是例子:

<?xml version="1.0" encoding="utf-8"?>
<manifest . . . >
<application . . . >
<activity android:name="com.example.project.FreneticActivity"
android:icon="@drawable/small_pic.png"
android:label="@string/freneticLabel"
. . . >
<intent-filter . . . >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter . . . >
<action android:name="com.example.project.BOUNCE" />
<data android:mimeType="image/jpeg" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
. . .
</application>
</manifest>

原文參考:


Comments

Popular posts from this blog

[Linux] UVC Camera

UPnP Device Implementations

[UPnP] UPnP Implementers Corporation & UPnP Forum