一、 Service簡介
Service是android 系統中的四大組件之一(Activity、Service、BroadcastReceiver、ContentProvider),它跟Activity的級別差不多,但不能自己運行只能後臺運行,並且可以和其他組件進行交互。service可以在很多場合的應用中使用,比如播放多媒體的時候用戶啓動了其他Activity這個時候程序要在後臺繼續播放,比如檢測SD卡上文件的變化,再或者在後臺記錄你地理信息位置的改變等等,總之服務總是藏在後臺的。
Service的啓動有兩種方式:context.startService() 和 context.bindService()
二、 Service啓動流程
context.startService() 啓動流程:
context.startService() -> onCreate() -> onStart() -> Service running -> context.stopService() -> onDestroy() -> Service stop
如果Service還沒有運行,則android先調用onCreate(),然後調用onStart();
如果Service已經運行,則只調用onStart(),所以一個Service的onStart方法可能會重複調用多次。
如果stopService的時候會直接onDestroy,如果是調用者自己直接退出而沒有調用stopService的話,Service會一直在後臺運行,該Service的調用者再啓動起來後可以通過stopService關閉Service。
所以調用startService的生命週期爲:onCreate --> onStart (可多次調用) --> onDestroycontext.bindService()啓動流程:
context.bindService() -> onCreate() -> onBind() -> Service running -> onUnbind() -> onDestroy() -> Service stoponBind()將返回給客戶端一個IBind接口實例,IBind允許客戶端回調服務的方法,比如得到Service的實例、運行狀態或其他操作。這個時候把調用者(Context,例如Activity)會和Service綁定在一起,Context退出了,Srevice就會調用onUnbind->onDestroy相應退出。
所以調用bindService的生命週期爲:onCreate --> onBind(只一次,不可多次綁定) --> onUnbind --> onDestory。
在Service每一次的開啓關閉過程中,只有onStart可被多次調用(通過多次startService調用),其他onCreate,onBind,onUnbind,onDestory在一個生命週期中只能被調用一次。
三、 Service生命週期
Service的生命週期並不像Activity那麼複雜,它只繼承了onCreate()、onStart()、onDestroy()三個方法
當我們第一次啓動Service時,先後調用了onCreate()、onStart()這兩個方法;當停止Service時,則執行onDestroy()方法。
這裏需要注意的是,如果Service已經啓動了,當我們再次啓動Service時,不會在執行onCreate()方法,而是直接執行onStart()方法。
它可以通過Service.stopSelf()方法或者Service.stopSelfResult()方法來停止自己,只要調用一次stopService()方法便可以停止服務,無論調用了多少次的啓動服務方法。
四、 Service示例
下面我做了一個簡單的音樂播放的應用,分別使用startService和bindService來啓動本地的服務。
Activity
- public class PlayMusicService extends Activity implements OnClickListener {
- private Button playBtn;
- private Button stopBtn;
- private Button pauseBtn;
- private Button exitBtn;
- private Button closeBtn;
- private Intent intent;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.music_service);
- playBtn = (Button) findViewById(R.id.play);
- stopBtn = (Button) findViewById(R.id.stop);
- pauseBtn = (Button) findViewById(R.id.pause);
- exitBtn = (Button) findViewById(R.id.exit);
- closeBtn = (Button) findViewById(R.id.close);
- playBtn.setOnClickListener(this);
- stopBtn.setOnClickListener(this);
- pauseBtn.setOnClickListener(this);
- exitBtn.setOnClickListener(this);
- closeBtn.setOnClickListener(this);
- }
- @Override
- public void onClick(View v) {
- int op = -1;
- intent = new Intent("com.homer.service.musicService");
- switch (v.getId()) {
- case R.id.play: // play music
- op = 1;
- break;
- case R.id.stop: // stop music
- op = 2;
- break;
- case R.id.pause: // pause music
- op = 3;
- break;
- case R.id.close: // close activity
- this.finish();
- break;
- case R.id.exit: // stopService
- op = 4;
- stopService(intent);
- this.finish();
- break;
- }
- Bundle bundle = new Bundle();
- bundle.putInt("op", op);
- intent.putExtras(bundle);
- startService(intent); // startService
- }
- @Override
- public void onDestroy(){
- super.onDestroy();
- if(intent != null){
- stopService(intent);
- }
- }
- }
Service
- public class MusicService extends Service {
- private static final String TAG = "MyService";
- private MediaPlayer mediaPlayer;
- @Override
- public IBinder onBind(Intent arg0) {
- return null;
- }
- @Override
- public void onCreate() {
- Log.v(TAG, "onCreate");
- Toast.makeText(this, "show media player", Toast.LENGTH_SHORT).show();
- if (mediaPlayer == null) {
- mediaPlayer = MediaPlayer.create(this, R.raw.tmp);
- mediaPlayer.setLooping(false);
- }
- }
- @Override
- public void onDestroy() {
- Log.v(TAG, "onDestroy");
- Toast.makeText(this, "stop media player", Toast.LENGTH_SHORT);
- if (mediaPlayer != null) {
- mediaPlayer.stop();
- mediaPlayer.release();
- }
- }
- @Override
- public void onStart(Intent intent, int startId) {
- Log.v(TAG, "onStart");
- if (intent != null) {
- Bundle bundle = intent.getExtras();
- if (bundle != null) {
- int op = bundle.getInt("op");
- switch (op) {
- case 1:
- play();
- break;
- case 2:
- stop();
- break;
- case 3:
- pause();
- break;
- }
- }
- }
- }
- public void play() {
- if (!mediaPlayer.isPlaying()) {
- mediaPlayer.start();
- }
- }
- public void pause() {
- if (mediaPlayer != null && mediaPlayer.isPlaying()) {
- mediaPlayer.pause();
- }
- }
- public void stop() {
- if (mediaPlayer != null) {
- mediaPlayer.stop();
- try {
- mediaPlayer.prepare(); // 在調用stop後如果需要再次通過start進行播放,需要之前調用prepare函數
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- }
- }
AndroidManifest.xml
註冊activity
- <activity
- android:name=".service.PlayMusicService"
- android:label="@string/app_name" />
註冊service
- <service
- android:name=".service.MusicService"
- android:enabled="true" >
- <intent-filter>
- <action android:name="com.homer.service.musicService" />
- </intent-filter>
- </service>
五、 代碼解析
1、Activity中,PlayMusicService中通過重寫OnClickListener 接口onClick()方法實現對播放音樂的控制,把音樂各種操作用數字通過Intent傳遞給service
然後通過構造一個Intent , intent = new Intent("com.homer.service.musicService");
其中,com.homer.service.musicService是 AndroidManifest.xml 對service的定義,即上面“註冊service”
2、Activity中,音樂播放的控制,利用Bundle綁定數字op後,通過 startService(intent); 服務後發送出去Bundle bundle = new Bundle();
bundle.putInt("op", op);
intent.putExtras(bundle);
startService(intent);
3、 Service中,會處理Activity啓動的 startService(intent);服務,依次調用service的啓動過程:onCreate --> onStart(可多次調用) --> onDestroy
onCreate(), 創建mediaPlayer
onStart(), 通過獲取Bundle bundle = intent.getExtras();,提取int op = bundle.getInt("op");,然後執行響應的音樂播放操作
onDestroy(),停止並釋放mediaPlayer音樂資源,如果當執行context.stopService()時調用此方法
4、Activity中,onClick()函數中close與exit是執行含義是不同的:
close : 只是執行了this.finish(); 關閉了本Activity窗體,service並沒有被關掉,音樂依然會繼續在後臺播放
exit : 先調用了stopService(intent); 關閉了service服務,在Service中會調用3中的onDestroy()停止並釋放音樂資源,後才執行this.finish(); 關閉了本Activity窗體
六、 拓展知識(進程和聲明週期)
Android操作系統嘗試儘可能長時間的保持應用的進程,但當可用內存很低時最終要移走一部分進程。怎樣確定那些程序可以運行,那些要被銷燬,Android讓每一個進程在一個重要級的基礎上運行,重要級低的進程最有可能被淘汰,一共有5級,下面這個列表就是按照重要性排列的:
1 一個前臺進程顯示的是用戶此時需要處理和顯示的。下列的條件有任何一個成立,這個進程都被認爲是在前臺運行的。
a 與用戶正發生交互的。
b 它控制一個與用戶交互的必須的基本的服務。
c 有一個正在調用生命週期的回調函數的service(如onCreate()、onStar()、onDestroy())
d 它有一個正在運行onReceive()方法的廣播接收對象。
只有少數的前臺進程可以在任何給定的時間內運行,銷燬他們是系統萬不得已的、最後的選擇——當內存不夠系統繼續運行下去時。通常,在這一點上,設備已經達到了內存分頁狀態,所以殺掉一些前臺進程來保證能夠響應用戶的需求。
2 一個可用進程沒有任何前臺組件,但它仍然可以影響到用戶的界面。下面兩種情況發生時,可以稱該進程爲可用進程。
它是一個非前臺的activity,但對用戶仍然可用(onPause()方法已經被調用)這是可能發生的,例如:前臺的activity是一個允許上一個activity可見的對話框,即當前activity半透明,能看到前一個activity的界面,它是一個服務於可用activity的服務。
3 一個服務進程是一個通過調用startService()方法啓動的服務,並且不屬於前兩種情況。儘管服務進程沒有直接被用戶看到,但他們確實是用戶所關心的,比如後臺播放音樂或網絡下載數據。所以系統保證他們的運行,直到不能保證所有的前臺可見程序都正常運行時纔會終止他們。
4 一個後臺進程就是一個非當前正在運行的activity(activity的onStop()方法已經被調用),他們不會對用戶體驗造成直接的影響,當沒有足夠內存來運行前臺可見程序時,他們將會被終止。通常,後臺進程會有很多個在運行,所以他們維護一個LRU最近使用程序列表來保證經常運行的activity能最後一個被終止。如果一個activity正確的實現了生命週期的方法,並且保存它當前狀態,殺死這些進程將不會影響到用戶體驗。
5 一個空線程沒有運行任何可用應用程序組,保留他們的唯一原因是爲了設立一個緩存機制,來加快組件啓動的時間。系統經常殺死這些內存來平衡系統的整個系統的資源,進程緩存和基本核心緩存之間的資源。
Android把進程裏優先級最高的activity或服務,作爲這個進程的優先級。例如,一個進程擁有一個服務和一個可見的activity,那麼這個進程將會被定義爲可見進程,而不是服務進程。
此外,如果別的進程依賴某一個進程的話,那麼被依賴的進程會提高優先級。一個進程服務於另一個進程,那麼提供服務的進程不會低於獲得服務的進程。例如,如果進程A的一個內容提供商服務於進程B的一個客戶端,或者進程A的一個service被進程B的一個組件綁定,那麼進程A至少擁有和進程B一樣的優先級,或者更高。
因爲一個運行服務的進程的優先級高於運行後臺activity的進程,一個activity會準備一個長時間運行的操作來啓動一個服務,而不是啓動一個線程–尤其是這個操作可能會拖垮這個activity。例如後臺播放音樂的同時,通過照相機向服務器發送一張照片,啓動一個服務會保證這個操作至少運行在service 進程的優先級下,無論這個activity發生了什麼,廣播接收者應該作爲一個空服務而不是簡單的把耗時的操作單獨放在一個線程裏。