android四大組件之service

Service服務與Activity有些像,就像個沒有界面的activity,它也是Context的子類,可以自定義一個類繼承Service,
它的生命週期如下:
onCreate():第一次創建調用
onStartCommand(Intent intent,int flags,int startId):通過startService啓動時才調用,每次啓動都會調用
onDestory():關閉時調用
onBind(Intent intent):與程序通信使用,綁定service只會調用一次
onUnbind(Intent intent):與service綁定的連接全部斷開時調用
類似註冊activity,我們也要在配置文件中加入<service>標籤,其也可以設置intent-filter等,有兩種
方法可以啓動service:
Context.startService():啓動service,但這種啓動訪問者即使退出該service依然會運行,想終止可調用
stopService(Intent intent)方法,由於訪問者與service無關聯,所以不能通信或傳數據
Context.bindService():綁定service,訪問者退出service也會停止,unbindService終止,可以進行通信
bindService(Intent service,ServiceConnection conn,int flags);Intent指定要啓動的service,conn
主要用於監聽連接情況,當service連接成功會調onServiceConnected(ComponentName name,IBinder service)
方法,這裏參數的IBinder對象就是在onBind方法返會的對象,所以想通信就靠它了,當service終止會調onServiceDisconnected(ComponentName name)方法,flags指定綁定時是否自動創建service,0爲不自動創建,BIND_AUTO_CREATE爲自動創建
所以這兩種方式的生命週期大概就是:
startService:onCreate-onStartCommand-onDestory
bindService:onCreate-onBind-onUnbind-onDestory
雖然service看似是獨立的,但它並不是一個新的進程或線程,所以我們不能直接在裏面進行耗時操作,如果要

執行耗時操作則需要創建一個新線程

IntentService是Service的子類,主要解決了在service中不能直接執行耗時操作的問題,intentService是用
隊列來管理intent,它會將intent加入隊列並開啓新線程,這樣不會造成主線程的阻塞。
使用非常簡單,直接繼承IntentService並重寫onHandleIntent方法就可以,無需寫onBind和onStartCommand
public class MyService extends IntentService{
@Override
protected void onHandleIntent(Intent intent){
//這裏可以直接執行耗時操作
}
}

發佈了36 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章