Android Services(服務)可以在不用使用 使用者介面下 在背景提供長期的服務 例如下載檔案 或撥放音樂 甚至與遠程伺服器通訊 等等 並且有些服務即使關掉APP 仍然會在背後持續運行
前景服務的運行 可以透過startService() 來去啟動 通常會讓使用者知道該服務正在運行 即使將應用程式最小化 他還是會繼續運行 例如 導航或音樂撥放器
背景服務不與使用者交互 在Android API 26(Android 8)之後 並不允許 Background Service 運行 除非該用程式在前景 來解決耗電問題
Bound Service 是android 特殊類型的服務 他提供clinet 與 server 模型 讓其他應用程式組件透過IPC來進行通訊互動
服務擴展
public class ExampleService extends Service {
int startMode; // indicates how to behave if the service is killed
IBinder binder; // interface for clients that bind
boolean allowRebind; // indicates whether onRebind should be used
...
}
}
Foreground Servcie 與 Bound Service 建立流程
Service 也會宣告在 AndroidManifest.xml 中
<manifest ...>
<application ...>
<service android:name=".testForegroundService"/>
<service android:name=".testBackgroundService"/>
</application>
</manifest>