Android -- Service

來源:互聯網
上載者:User

標籤:

@、Context.startService(Intent)

lifecycle callback:

1、onCreate(...)

2、onStartCommande(Intent, int, int)

3、onDestroy()

stop service:

1、Service.stopSelf() / stopSelf(int)

2、Context.stopService(Intent)

 

@、Context.bindService

lifecycle callback:

1、onBind(...)

2、onUnbind()

stop service:

1、Context.unbindService() (當所有用戶端都執行完此操作,服務會自動關閉,除了調用Service.startForeground()的情況。)

 

@、保持Service不被終止

在服務裡調用startForeground(),這種情況要正確調用stopForeground()來終止服務,否則服務一直運行。

 

@、與Activity通訊:

1、使用sendBroadcast(Intent)。

2、在Service中添加會調介面及介面執行個體及執行個體的set方法,而Activity實現此介面。這種方法可結合Locally Bound Service模式進行使用,這樣可以在Activity中直接調用Service的方法。

 

@、IntentService

1、HandlerThread,Handler,Message模式。

2、繼承IntentService只需要實現onHandleIntent(Intent)方法。

3、以上兩點決定了,使用IntentService不用再建立線程,而onHandleIntent每次只能處理一個Intent,因此如果存在耗時間長度的Intent,則此IntentService的其他Intent就有可能被阻塞。

 

@、自訂Service實現並行服務

1、在自訂Service中添加ExecutorService執行個體成員,通過它的excute(Runnable)來執行任務。通過startForeground(),保持服務後台運行,通過計數成員變數記錄當前任務數量,根據當前任務數量決定是否調用stopForeground()來終止服務。

 

註:關於Service的樣本見Android Programming: Pushing the Limits -- Chapter 6: Services and Background Tasks。

 

Android -- Service

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.