2011年4月6日 星期三

Service類別

Service類別
Service沒有提供與用戶進行互動的展示層,為一背景執行的程式,一般來說,若是不需要UI操作的程序則可使用Service來完成。

Service一般是由Activity或Context物件來啟動,啟動的方式分為二種:
    透過startService()啟動:啟動後直到Service呼叫自身的stopSelf或stopService時才停止
    透過bindService()啟動:當綁定的Context被銷毀時,停止執行

生命週期如下所示:
程式碼
    public class ExampleService extends Service {
        int mStartMode;       // indicates how to behave if the service is killed
       
IBinder mBinder;      // interface for clients that bind
       
boolean mAllowRebind; // indicates whether onRebind should be used

        public void onCreate() {
           
// The service is being created
       
}
       
public int onStartCommand(Intent intent, int flags, int startId) {
           
// The service is starting, due to a call to startService()
           
return mStartMode;
       
}
        public IBinder onBind(Intent intent) {
           
// A client is binding to the service with bindService()
           
return mBinder;
       
}
       
public boolean onUnbind(Intent intent) {
           
// All clients have unbound with unbindService()
           
return mAllowRebind;
       
}
        public void onRebind(Intent intent) {
           
// A client is binding to the service with bindService(),
           
// after onUnbind() has already been called
       
}
       
public void onDestroy() {
           
// The service is no longer used and is being destroyed
       
}
    }

3 則留言:

  1. hello
    我發現你的文章寫的不錯 簡潔
    這些都是你測試過可以work的code吧?

    對拉 我可以請教你一各問題嗎
    我想要在背景偵測音量鍵按下 然後觸發一各程式
    你會用service來實行嗎?
    謝謝

    回覆刪除
  2. 抱歉,有一陣子沒上來了
    現在才看到你的問題

    這個問題主要可以分為2部分
    1. 啟動service的Activity
    利用startService/stopService來控制service的開關
    可以參考"Intent & Bundle物件"文章。
    2. service
    這裡需要使用到keyevent的function
    在service裡加入key值的判斷
    請參照"KeyEven接收"文章
    當音量鍵按下後需觸發另一個Activity
    這時則需要改用"PendingIntent"這個物件
    因為在service裡startActivity是無法使用的
    這個部份一樣在"Intent & Bundle物件"有寫到

    回覆刪除
  3. Harvey 先謝過 我實作看看 成功後在貼上來

    回覆刪除