Service
Service是Android系統(tǒng)的后臺(tái)服務(wù)組件,適用于開發(fā)無(wú)界面、長(zhǎng)時(shí)間運(yùn)行的應(yīng)用功能
特點(diǎn)
1)沒(méi)有用戶界面
2)比Activity的優(yōu)先級(jí)高,不會(huì)輕易被Android系統(tǒng)終止
3)即使Service被系統(tǒng)終止,在系統(tǒng)資源恢復(fù)后Service也將自動(dòng)恢復(fù)運(yùn)行狀態(tài)
4)用于進(jìn)程間通信(Inter Process Communication,IPC),解決兩個(gè)不同Android應(yīng)用程序進(jìn)程之間的調(diào)用和通訊問(wèn)題
Service生命周期包括全生命周期、活動(dòng)生命周期
onCreate()事件回調(diào)函數(shù):Service的生命周期開始,完成Service的初始化工作
onStart()事件回調(diào)函數(shù):活動(dòng)生命周期開始,但沒(méi)有與之對(duì)應(yīng)的“停止”函數(shù),因此可以近似認(rèn)為活動(dòng)生命周期也是以onDestroy()標(biāo)志結(jié)束
onDestroy()事件回調(diào)函數(shù):Service的生命周期結(jié)束,釋放Service所有占用的資源
顯示啟動(dòng):在Intent中指明Service所在的類,并調(diào)用startService(Intent)函數(shù)啟動(dòng)Service
final Intent serviceIntent = new Intent(this, RandomService.class);
startService(serviceIntent);
隱式啟動(dòng) :在注冊(cè)Service時(shí),聲明Intent-filter的action屬性
隱式啟動(dòng)的代碼如下
final Intent serviceIntent = new Intent();
serviceIntent.setAction("edu.hrbeu.RandomService");
實(shí)現(xiàn)Service的最小代碼集
第1行到第3行引入必要包
第5行聲明了RandomService繼承android.app.Service類
在第7行到第9行重載了onBind()函數(shù)
onBind()函數(shù)是在Service被綁定后調(diào)用的函數(shù),能夠返回Service的對(duì)象,在后面的內(nèi)容中會(huì)詳細(xì)介紹
Service的最小代碼集并不能完成任何實(shí)際的功能,需要重載onCreate()、onStart()和onDestroy(),才使Service具有實(shí)際意義
?????Android系統(tǒng)在創(chuàng)建Service時(shí),會(huì)自動(dòng)調(diào)用onCreate()完成必要的初始化工作
在Service沒(méi)有必要再存在時(shí),系統(tǒng)會(huì)自動(dòng)調(diào)用onDestroy(),釋放所有占用的資源
通過(guò)Context.startService(Intent)啟動(dòng)Service時(shí),onStart()則會(huì)被系統(tǒng)調(diào)用,Intent會(huì)傳遞給Service一些重要的參數(shù)
注冊(cè)Service
在AndroidManifest.xml文件中注冊(cè),否則,這個(gè)Service根本無(wú)法啟動(dòng)
AndroidManifest.xml文件中注冊(cè)Service的代碼如下
啟動(dòng)Service
顯示啟動(dòng):在Intent中指明Service所在的類,并調(diào)用startService(Intent)函數(shù)啟動(dòng)Service,示例代碼如下
final Intent serviceIntent = new Intent(this, RandomService.class);
startService(serviceIntent);
在Intent中指明啟動(dòng)的Service在RandomSerevice.class中
隱式啟動(dòng):在注冊(cè)Service時(shí),聲明Intent-filter的action屬性
設(shè)置Intent的action屬性,可以在不聲明Service所在類的情況下啟動(dòng)服務(wù)隱式啟動(dòng)的代碼如下
final Intent serviceIntent = new Intent();
serviceIntent.setAction("edu.hrbeu.RandomService");
若Service和調(diào)用服務(wù)的組件在同一個(gè)應(yīng)用程序中,可以使用顯式啟動(dòng)或隱式啟動(dòng),顯式啟動(dòng)更加易于使用,且代碼簡(jiǎn)潔若服務(wù)和調(diào)用
服務(wù)的組件在不同的應(yīng)用程序中,則只能使用隱式啟動(dòng)
停止Service
將啟動(dòng)Service的Intent傳遞給stopService(Intent)函數(shù)即可,
示例代碼如下
stopService(serviceIntent);
在調(diào)用startService(Intent)函數(shù)首次啟動(dòng)Service后,系統(tǒng)會(huì)先后調(diào)用onCreate()和onStart()
再次調(diào)用startService(Intent)函數(shù),系統(tǒng)則僅調(diào)用onStart(),而不再調(diào)用onCreate()
在調(diào)用stopService(Intent)函數(shù)停止Service時(shí),系統(tǒng)會(huì)調(diào)用onDestroy()
無(wú)論調(diào)用過(guò)多少次startService(Intent),在調(diào)用stopService (Intent)函數(shù)時(shí),系統(tǒng)僅調(diào)用onDestroy()一次