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

Android Service 教學:生命週期、startService 與 bindService

編輯:關於 Android 程式設計

Service 是 Android 四大元件之一,適合執行不需要使用者介面的背景工作,例如音樂播放、檔案下載或長時間運算。

兩種啟動方式

  • startService:呼叫 onCreate 與 onStart,停止時呼叫 onDestroy。
  • bindService:呼叫 onCreate 與 onBind,解除綁定後依情境銷毀。
startService(new Intent(this, MusicService.class));
bindService(new Intent(this, MusicService.class), connection, Context.BIND_AUTO_CREATE);

若希望 Service 與 Activity 生命週期脫鉤,可優先使用 startService;若需要直接呼叫 Service 方法,則 bindService 更合適。

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