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

Android Activity 與 Service 資料互動:bindService 實作

編輯:關於 Android 開發

Activity 與 Service 互動

Android 中啟動 Service 主要有 startService 與 bindService。startService 適合背景任務;bindService 適合 Activity 需要與 Service 即時溝通。

使用 bindService 時,Service 會透過 onBind 回傳 Binder。Activity 可在 onServiceConnected 中取得 Service 實例,並註冊回呼介面,例如進度監聽器。Service 在背景更新進度時,可呼叫 listener,讓 Activity 更新 ProgressBar。

使用完畢後,Activity 應在 onDestroy 中呼叫 unbindService,避免資源洩漏。若同時使用 startService 與 bindService,需分別停止與解除綁定,Service 才會結束。

若需要跨進程溝通,則需使用 AIDL。

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