Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 開發入門:Service 初步

編輯:初階開發

Service 是 Android 四大組件之一,也是初學者最容易搞錯觀念的一個。本文從「它是什麼」、「它不是什麼」開始,再談實作與生命週期。

一、Service 是什麼

  • Service 是一個應用程式組件。
  • Service 沒有圖形化介面。
  • Service 通常用來處理耗時較久的操作。
  • 可以用 Service 更新 ContentProvider、發送 Intent,以及啟動系統通知。

二、Service 不是什麼(重點觀念)

  • Service 不是一個獨立的進程。它預設運行在應用的主進程中,與 Activity 共享同一個 process。
  • Service 不是一個線程。它運行在應用主線程(UI 線程)上,因此不能在 Service 中直接執行長時間的阻塞運算,否則會造成畫面卡頓甚至 ANR。正確做法是在 Service 內部另開背景線程或改用 IntentService/JobIntentService。

這兩點是面試與實務中最常考的地方,务必記牢。

三、實作 Service

先繼承 Service,然後實作以下方法:

onBind()
onCreate()
onStartCommand()
onDestroy()

接著必須在 AndroidManifest.xml 中註冊,否則系統無法找到它:

<service android:name=".FirstService"></service>

四、在 Activity 中啟動與關閉 Service

啟動:

Intent intent = new Intent();
intent.setClass(TestActivity.this, FirstService.class);
startService(intent);

關閉:

Intent intent = new Intent();
intent.setClass(TestActivity.this, FirstService.class);
stopService(intent);

Service 也可以在內部呼叫 stopSelf() 自行結束。

五、Service 的生命週期

透過 startService() 啟動時的順序如下:

  1. 第一次建立 Service 對象時,會先呼叫 onCreate()。
  2. 接著呼叫 onStartCommand(),這個函數會收到 Intent 對象,可以從中取得資料。
  3. 此時若再次啟動同一個 Service,不會再呼叫 onCreate(),而是直接呼叫 onStartCommand()——因為上一次的 Service 並沒有被銷毀。
  4. 當不再需要這個 Service 時,在 Activity 中呼叫 stopService(),系統就會呼叫 Service 的 onDestroy()。

若改用 bindService() 啟動,生命週期順序會變成 onCreate() → onBind() → onDestroy(),並且需要透過 ServiceConnection 來取得與 Service 溝通的 Binder。

六、onStartCommand 的回傳值

一個容易被忽略但很重要的細節:onStartCommand() 必須回傳一個整數,用來告訴系統「若 Service 被系統殺掉,該怎麼處理」。常見選項有:

  • START_STICKY:Service 被殺後會重建,但 Intent 會是 null。
  • START_NOT_STICKY:被殺就這樣,不重建。
  • START_REDELIVER_INTENT:重建並重新送來最後一個 Intent。

選錯回傳值,可能導致 Service 莫名重啟或該跑的任務沒跑完,實作時要依需求判斷。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved