jollen.org

Jollen 的 Blog
Jollen's email: jollen # jollen.org
more:  Jollen's Training

Jollen 的 Android 教學,#8: 沒有 UI 的 Service

.作者:jollen/
.日期:January 12, 2009 3:15 PM


到目前為止,我們都著重在 Activity 以及 UI 的介紹,在 Android 應用程式裡,有一種沒有 UI 的類別(android.app.Service),稱之為 Service。簡單來說,Service 是一個 background process(背景程序),透過背景程序,我們可以實作一些不需要 UI 的功能,例如:在背景撥放音樂。

以下是利用 Eclipse 環境自動產生的類別 'MokoService':

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MokoService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}

MokoService 類別繼承自 android.app.Service,幾個有關 Service 的重要觀念如下:

1. Service 物件以 separated process 的方式執行,這表示 Service 與 UI(Activity)並不在同一個 process 裡執行,而是個自在不同的 process 執行。

2. Android 應用程式是在 Activity 裡啟動與停止 Service。

3. 覆載(override)onStart() 方法(method)在 Service 被啟動時,執行我們想要的背景功能。

4. 覆載 onDestroy() 方法在 Service 被停止時,停止執行中的背景功能。

以下是一個加入 onStart 與 onDestroy 的 MokoService 實作:

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MokoService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		
	}
	
	@Override
	public void onDestroy() {
		
	}
}
目前,我們了解 Activity 與 Service 的觀念了,接下來,要怎麼在 Activity 裡啟動 Service 呢?

Tags:

純手工打造說明:技術專欄文章為 Jollen 原創,內容皆為人工撰寫,無 AI 生成。轉載請註明出處與作者,並全文引用。轉載時請在文章開頭或結尾明顯處註明「本文出處:https://www.jollen.org,已取得原作者同意並授權使用。」
訂閱電子報:不定期 Jollen's Blog 精選文章隨 Moko365 電子報寄送;請透過 Moko365 電子報訂閱(可隨時取消)。

Copyright(c) 2001–2009 www.jollen.org. All rights reserved.
Last update: 2026-07-22