以下是利用 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 呢?
現在我們想要在 Activity 裡載入並啟動 MokoService 類別,讓它可以在背景執行,請依以下步驟完成這個任務。。
修改 AndroidManifest.xml
在 Package Explorer 視窗裡找到目前 Android 專案的資訊描述檔,檔名是 AndroidManifest.xml。這是一個用來描述 Android 應用程式「整體資訊」的檔案,每個 Android 應用程式專案都會有一個。在這裡修改 Androidmanifest.xml 的目的是為了「在我們的 Android 應用程式裡加入一個 Service 類別」,這樣才有辦法啟動 Service。修改後的內容如下,紅色的部份是新增的描述:
|
啟動 Service - startService()
回到 HelloM 類別,加入一行程式碼:
|
startService(Intent service)
呼叫 startService() 即可啟動一個 Service 類別,只是,startService() 的參數是一個「Intent」的型別,並不是所要啟動的類別名稱。「Intent」是一個很像「Event」的類別,後續我們再做比較精確的說明,在這裡,我們不如把 Intent 當成是 Event(事件)。
當程式送出 com.moko.hello.START_MUSIC 事件給 Android 時,Android 便去尋找能處理此事件的類別,然後啟動它。在這裡,能處理 com.moko.hello.START_MUSIC 事件的類別就是 MokoService,這個關係就是透過 AndroidManifest.xml 的設定實現的。
引用連結:
http://www.jollen.org/cgi-bin/mt3/mt-tb.cgi/602
http://www.jollen.org/cgi-bin/mt3/mt-tb.cgi/603
0 comments:
Post a Comment