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

Android Service 全面解析:從生命週期到前台服務

編輯:關於 Android 程式設計

Service 是一種可在後台執行長時間操作、且無需用戶界面的應用組件。它可由其他應用組件啟動,即便用戶切換到別的應用,Service 仍會在後台持續運行。此外,組件還能綁定到 Service 以與之交互,甚至執行進程間通信(IPC)。舉例來說,Service 可以處理網絡事務、播放音樂、執行文件 I/O 或與內容提供程序交互,而這一切都能在後台默默進行。

生命週期

官方圖解如下:

 

 

onStartCommand()

當另一個組件(如 Activity)透過調用 startService() 請求啟動服務時,系統會調用此方法。一旦執行,服務即啟動並可在後台無限期運行。若你實現了此方法,則在服務工作完成後,需自行透過調用 stopSelf() 或 stopService() 來停止服務。(如果你只想提供綁定,則無需實現此方法。)

onBind()

當另一個組件想透過調用 bindService() 與服務綁定(例如執行 RPC)時,系統會調用此方法。在此方法的實現中,你必須透過返回 IBinder 提供一個供客戶端與服務通信的接口。請務必實現此方法,但如果你並不希望允許綁定,則應返回 null。

onCreate()

首次創建服務時,系統會調用此方法執行一次性設置(在調用 onStartCommand() 或 onBind() 之前)。如果服務已在運行,則不會調用此方法。

onDestroy()

當服務不再被使用、即將銷毀時,系統會調用此方法。服務應在此清理所有資源,如線程、注冊的偵聽器、接收器等。這是服務接收的最後一次調用。

Service 的基本用法

關於 Service 最基本的用法,自然是如何啟動一個 Service。啟動 Service 的方式與啟動 Activity 頗為相似,都需借助 Intent 來實現。下面我們透過一個具體示例來一探究竟。

新建一個名為 ServiceTest 的 Android 項目,這裡我選擇使用 4.0 的 API。

接著新建一個繼承自 Service 的 MyService,並重寫父類的 onCreate()、onStartCommand() 和 onDestroy() 方法,如下所示:

    ……    

這樣,一個簡單的、帶有 Service 功能的程序就寫好了。我們將程序運行起來,點擊一下 Start Service 按鈕,可以看到 LogCat 的打印日志如下:

MyService onCreate() executed
MyService onStartCommand() executed

也就是說,當啟動一個 Service 時,會調用該 Service 中的 onCreate() 和 onStartCommand() 方法。

那麼,如果我再點擊一次 Start Service 按鈕呢?此時的打印日志如下:

MyService onStartCommand() executed

可以看到,這次只有 onStartCommand() 方法執行了,onCreate() 並未執行。為什麼會這樣?這是因為 onCreate() 只會在 Service 第一次被創建時調用;一旦 Service 已被創建過,無論你怎樣調用 startService(),onCreate() 都不會再觸發。因此你可以多點幾次 Start Service 驗證一下,每次都只會有 onStartCommand() 裡的打印日志。

我們還能到手機的應用程序管理界面去確認 MyService 是否正在運行,如下圖所示:

 

 

的確,MyService 正在運行,哪怕它內部並未執行任何邏輯。

回到 ServiceTest 程序,點擊一下 Stop Service 按鈕,就能把 MyService 停止掉。

Service 與 Activity 通信

上面我們學習了 Service 的基本用法——啟動 Service 後,就能在 onCreate() 或 onStartCommand() 裡執行具體邏輯。不過這樣一來,Service 與 Activity 的關聯並不大,Activity 只是通知了 Service 一聲:「你可以啟動了。」然後 Service 就忙自己的事去了。那有沒有辦法讓二者關聯得更緊密些呢?比如在 Activity 中指定讓 Service 執行某項任務。當然可以,只需讓 Activity 與 Service 建立關聯即可。

觀察 MyService 中的代碼,你會發現一直有個 onBind() 方法沒被用到,而它正是用於和 Activity 建立關聯的。修改 MyService 的代碼,如下所示:

 public class MyService extends Service { public static final String TAG = "MyService"; private MyBinder mBinder = new MyBinder(); @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate() executed"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "onStartCommand() executed"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy() executed"); } @Override public IBinder onBind(Intent intent) { return mBinder; } class MyBinder extends Binder { public void startDownload() { Log.d("TAG", "startDownload() executed"); // 執行具體的下載任務 } } } 

這裡我們新增了一個繼承自 Binder 的 MyBinder 類,並在其中添加了用於後台執行下載任務的 startDownload() 方法。當然這裡並非真正去下載什麼,只是做個測試,所以 startDownload() 僅打印了一行日志。

接著修改 activity_main.xml,在布局文件中添加用於綁定 Service 和取消綁定 Service 的按鈕:

 

再修改 MainActivity 的代碼,讓它與 MyService 建立關聯,代碼如下所示:

 public class MainActivity extends Activity implements OnClickListener { private Button startService; private Button stopService; private Button bindService; private Button unbindService; private MyService.MyBinder myBinder; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { } @Override public void onServiceConnected(ComponentName name, IBinder service) { myBinder = (MyService.MyBinder) service; myBinder.startDownload(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startService = (Button) findViewById(R.id.start_service); stopService = (Button) findViewById(R.id.stop_service); bindService = (Button) findViewById(R.id.bind_service); unbindService = (Button) findViewById(R.id.unbind_service); startService.setOnClickListener(this); stopService.setOnClickListener(this); bindService.setOnClickListener(this); unbindService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.start_service: Intent startIntent = new Intent(this, MyService.class); startService(startIntent); break; case R.id.stop_service: Intent stopIntent = new Intent(this, MyService.class); stopService(stopIntent); break; case R.id.bind_service: Intent bindIntent = new Intent(this, MyService.class); bindService(bindIntent, connection, BIND_AUTO_CREATE); break; case R.id.unbind_service: unbindService(connection); break; default: break; } } } 

可以看到,這裡我們首先創建了一個 ServiceConnection 匿名類,並在其中重寫了 onServiceConnected() 和 onServiceDisconnected() 方法,它們分別會在 Activity 與 Service 建立關聯和解除關聯時被調用。在 onServiceConnected() 中,我們透過向下轉型拿到了 MyBinder 的實例,有了它,Activity 與 Service 的關係就變得無比緊密了。現在我們可以在 Activity 中依具體場景調用 MyBinder 的任何 public 方法,也就實現了「Activity 指揮 Service 幹活、Service 就照辦」的效果。

當然,此時 Activity 與 Service 其實還沒關聯起來,這一步是在 Bind Service 按鈕的點擊事件裡完成的。可以看到,這裡我們同樣構建了一個 Intent 對象,然後調用 bindService() 方法把 Activity 與 Service 綁定。bindService() 接收三個參數:第一個是剛構建的 Intent 對象,第二個是前面創建的 ServiceConnection 實例,第三個是標志位——這裡傳入 BIND_AUTO_CREATE,表示 Activity 與 Service 建立關聯後自動創建 Service,這會使得 MyService 的 onCreate() 得到執行,但 onStartCommand() 不會執行。

那如果想解除 Activity 與 Service 的關聯呢?調用一下 unbindService() 方法即可,這也是 Unbind Service 按鈕點擊事件裡實現的邏輯。

現在重新運行程序吧。在 MainActivity 中點擊 Bind Service 按鈕,LogCat 裡的打印日志如下:

MyService onCreate() executed
MyService startDownload() executed

另外需注意,任何一個 Service 在整個應用程序範圍內都是通用的,即 MyService 不僅能與 MainActivity 建立關聯,還能與任何一個 Activity 建立關聯,而且建立關聯時它們都能拿到相同的 MyBinder 實例。

如何銷毀 Service

在 Service 基本用法那部分,我們介紹了銷毀 Service 最簡單的一種情形:點擊 Start Service 啟動,再點擊 Stop Service 停止,MyService 便被銷毀,打印日志如下:

MyService onCreate() executed
MyService onStartCommand() executed
MyService onDestroy() executed

那麼,如果我們點擊的是 Bind Service 按鈕呢?由於綁定時指定的標志位是 BIND_AUTO_CREATE,說明點擊 Bind Service 時 Service 也會被創建,這時又該如何銷毀?其實也很簡單,點擊一下 Unbind Service 按鈕,解除 Activity 與 Service 的關聯即可。

先點擊 Bind Service,再點擊 Unbind Service,打印日志如下:

MyService onCreate() executed
MyService startDownload() executed
MyService onDestroy() executed

以上兩種銷毀方式都很好理解。那如果我們既點擊了 Start Service,又點擊了 Bind Service 會怎樣?此時你會發現,無論是單獨點擊 Stop Service 還是 Unbind Service,Service 都不會被銷毀,必須兩個都點擊一下,Service 才會銷毀。也就是說,點擊 Stop Service 只會讓 Service 停止,點擊 Unbind Service 只會讓 Service 與 Activity 解除關聯;一個 Service 必須在既沒有和任何 Activity 關聯、又處於停止狀態時,才會被銷毀。

為驗證這一點,我們在 Stop Service 和 Unbind Service 的點擊事件裡各加一行打印日志:

 public void onClick(View v) { switch (v.getId()) { case R.id.start_service: Intent startIntent = new Intent(this, MyService.class); startService(startIntent); break; case R.id.stop_service: Log.d("MyService", "click Stop Service button"); Intent stopIntent = new Intent(this, MyService.class); stopService(stopIntent); break; case R.id.bind_service: Intent bindIntent = new Intent(this, MyService.class); bindService(bindIntent, connection, BIND_AUTO_CREATE); break; case R.id.unbind_service: Log.d("MyService", "click Unbind Service button"); unbindService(connection); break; default: break; } } 

重新運行程序,先點擊 Start Service,再點擊 Bind Service,這樣就把 Service 啟動起來並與 Activity 建立了關聯。然後點擊 Stop Service,Service 並不會銷毀;再點擊一下 Unbind Service,Service 便銷毀了,打印日志如下:

MyService onCreate() executed
MyService onStartCommand() executed
MyService startDownload() executed
MyService click Stop Service button
MyService click Unbind Service button
MyService onDestroy() executed

我們應當始終記得在 Service 的 onDestroy() 方法裡清理掉那些不再使用的資源,以防 Service 銷毀後仍有一些廢棄對象霸佔著內存。

Service 與 Thread 的關係

不少 Android 初學者都可能有這樣的困惑:Service 和 Thread 究竟是什麼關係?什麼時候該用 Service,什麼時候又該用 Thread?答案可能會讓你有點意外——因為 Service 和 Thread 之間毫無關係!

之所以有人會把它們聯繫起來,主要是因為 Service 的「後台」概念。Thread 大家都懂,用來開啟子線程,把耗時操作放在這裡執行就不會阻塞主線程。而我們最初理解 Service 時,總覺得它是用來處理後台任務的,一些耗時操作也能放在這裡跑,於是便產生了混淆。但我要告訴你:Service 其實是運行在主線程裡的,你還會覺得它和 Thread 有什麼關係嗎?讓我們看看這個「殘酷」的事實。

在 MainActivity 的 onCreate() 方法裡加入一行打印當前線程 id 的語句:

 Log.d("MyService", "MainActivity thread id is " + Thread.currentThread().getId()); 

然後在 MyService 的 onCreate() 方法裡也加入一行打印當前線程 id 的語句:

 Log.d("MyService", "MyService thread id is " + Thread.currentThread().getId()); 

現在重新運行程序,並點擊 Start Service 按鈕,會看到如下打印日志:

MyService MainActivity thread id is 1
MyService MyService thread id is 1

可以看到,它們的線程 id 完全一致,由此證實 Service 確實運行在主線程裡——這也就意味著,如果你在 Service 裡寫了非常耗時的代碼,程序必然會出現 ANR。

你可能會直呼「坑爹」,那要 Service 還有什麼用?其實,只要不把「後台」和「子線程」混為一談就行,這是兩個完全不同的概念。所謂 Android 的後台,指的是它的運行完全不依賴 UI——即使 Activity 被銷毀,或程序被關閉,只要進程還在,Service 就能繼續運行。比如某些應用需要與服務器始終保持心跳連接,就可以用 Service 來實現。你可能又會問:前面不是剛驗證過 Service 運行在主線程裡嗎?一直執行心跳連接,難道不會阻塞主線程?當然會,但我們可以在 Service 裡再開一個子線程,把耗時邏輯放到那裡處理就沒問題了。

既然如此,那為什麼不直接乾脆在 Activity 裡創建子線程呢?這是因為 Activity 很難對 Thread 進行控制——Activity 一旦被銷毀,就再也沒辦法重新拿到之前創建的子線程實例;而且在一個 Activity 裡創建的子線程,另一個 Activity 也無法操作。但 Service 就不同了,所有 Activity 都能與 Service 關聯,進而方便地操作其中的方法;即便 Activity 被銷毀,日後只要重新與 Service 建立關聯,又能拿到原有 Service 中 Binder 的實例。因此,用 Service 來處理後台任務,Activity 就能放心 finish,完全不必擔心後台任務失控。

一個比較標準的 Service 可以寫成:

 @Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(new Runnable() { @Override public void run() { // 開始執行後台任務 } }).start(); return super.onStartCommand(intent, flags, startId); } class MyBinder extends Binder { public void startDownload() { new Thread(new Runnable() { @Override public void run() { // 執行具體的下載任務 } }).start(); } } 

創建前台 Service

Service 幾乎都在後台默默運行,勤勤懇懇地幹著苦活累活。但 Service 的系統優先級相對較低,一旦系統內存吃緊,正在後台運行的 Service 就可能被回收。如果你希望 Service 能一直保持運行、不因內存不足而被回收,就可以考慮使用前台 Service。前台 Service 與普通 Service 最大的差別在於,它會在系統狀態欄一直顯示一個正在運行的圖標,下拉狀態欄後還能看到更詳細的信息,效果非常類似於通知。當然,你有時用前台 Service 並非只是為了防止被回收——有些項目出於特殊需求必須使用前台 Service,比如墨跡天氣,它的 Service 在後台更新天氣數據的同時,還會在狀態欄一直顯示當前天氣,如下圖所示:

 

 

那麼,如何才能創建一個前台 Service 呢?其實並不複雜,修改 MyService 中的代碼,如下所示:

 public class MyService extends Service { public static final String TAG = "MyService"; private MyBinder mBinder = new MyBinder(); @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate() executed"); Log.d("MyService", "MyService thread id is " + Thread.currentThread().getId()); Notification.Builder builder = new Notification.Builder(this); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); builder.setContentIntent(contentIntent); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setTicker("Foreground Service Start"); builder.setContentTitle("Foreground Service"); builder.setContentText("Make this service run in the foreground."); Notification notification = builder.build(); startForeground(BIND_AUTO_CREATE,notification); } ......... } 

這裡只改動了 MyService 的 onCreate() 方法。可以看到,我們首先創建了一個 Notification 對象,然後調用它的 setLatestEventInfo() 方法為通知初始化布局和數據,並設置點擊通知後打開 MainActivity,最後調用 startForeground() 方法,就能讓 MyService 變成一個前台 Service,並把通知圖標顯示出來。

現在重新運行程序,並點擊 Start Service 或 Bind Service 按鈕,MyService 便會以前台 Service 的模式啟動,同時系統狀態欄會彈出一個通欄圖標,下拉狀態欄後即可看到通知的詳細內容,如下圖所示:

 

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