iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0

Android Services(服務)可以在不用使用 使用者介面下 在背景提供長期的服務 例如下載檔案 或撥放音樂 甚至與遠程伺服器通訊 等等 並且有些服務即使關掉APP 仍然會在背後持續運行

前景服務(Foreground Service)

前景服務的運行 可以透過startService() 來去啟動 通常會讓使用者知道該服務正在運行 即使將應用程式最小化 他還是會繼續運行 例如 導航或音樂撥放器

背景服務(Background Service)

背景服務不與使用者交互 在Android API 26(Android 8)之後 並不允許 Background Service 運行 除非該用程式在前景 來解決耗電問題

繫結服務(Bound 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 建立流程
https://ithelp.ithome.com.tw/upload/images/20250923/20149459hDoFhUvg2u.png

Service 也會宣告在 AndroidManifest.xml 中

<manifest ...>
    <application ...>
        <service android:name=".testForegroundService"/>
        <service android:name=".testBackgroundService"/>
    </application>
</manifest>

上一篇
DAY 12 Activities 下
下一篇
Day 14 Broadcast Receivers
系列文
我是不可能一直學Android 絕對不會14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言