Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 從 Activity 中停止 Service 的做法

編輯:關於 Android 程式設計

Service 一旦啟動就會 independent 於頁面而存在,因此停止它的動作也必須由外部主動發出。最簡單的方式是從 Activity 呼叫 stopService(),並搭配 Action 字串定位到目標服務。

步驟一:在清單中註冊並標記 Action

<service android:name=".service.SensorService">
    <intent-filter>
        <action android:name="ITOP.MOBILE.SIMPLE.SERVICE.SENSORSERVICE"/>
    </intent-filter>
</service>

步驟二:在 Activity 中送出停止指令

final Intent intent = new Intent();
intent.setAction("ITOP.MOBILE.SIMPLE.SERVICE.SENSORSERVICE");
stopService(intent);

幾個實務細節

用 Action 字串比直接寫死類別名稱更有彈性,特別是同一支 Service 可能被多個模組共用時。但要留意:如果這個 Service 是以 bindService() 綁定的,單靠 stopService() 並不會真正終止它,還必須呼叫 unbindService() 解除綁定,否則服務會持續存活直到所有連線都斷開為止。

另外,Android 8.0 之後對背景服務有較嚴格的限制,長時間的常駐工作建議改用 Foreground Service 並顯示常駐通知,或改用 WorkManager 排程,這樣才能穩定通過系統的資源回收機制。

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