編輯:關於 Android 程式設計
前面介紹過 Activity 與 Intent,這次來談 Service。如果把 Activity 比喻成前台程式,那麼 Service 就是後台程式——它的整個生命週期都在後台執行。Service 和 Activity 一樣由 Intent 驅動。要在工程裡新增一個 Service,先寫一個繼承 Service 的類別,再到 AndroidManifest.xml 的 Application 節點下把它登記進來。
Service 需要由 Activity 透過 startService 或 bindService 啟動,參數則由 Intent 攜帶。
程式執行截圖:

本文重點在於 Service 的調用方式與生命週期變化。

上圖是 startService 之後再 stopService 的狀態變化。

上圖是 bindService 之後再 unbindService 的狀態變化。
兩種方式都能啟動 Service,差别在哪裡?關鍵是生命週期的歸屬。用 startService 啟動的 Service 必須由 stopService 收尾,否則就會出現 Activity 已經關掉、Service 卻還在跑的情況;用 bindService 啟動的 Service 除了可以 unbindService 解除,還能在宿主 Activity 走到 onDestroy 時自動結束。

上圖是 startService 之後直接 Activity.finish() 的狀態變化——Service 依然在跑。

上圖是 bindService 之後直接 Activity.finish() 的狀態變化——Service 最後自動完成 unbind。
main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnStartMyService" android:text="StartMyService"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnStopMyService" android:text="StopMyService"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnBindMyService" android:text="BindMyService"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnUnbindMyService" android:text="UnbindMyService"></Button> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnExit" android:text="退出程序"></Button> </LinearLayout>
testService.java:
package com.testService; import android.app.Activity; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.widget.Button; public class testService extends Activity { Button btnStartMyService,btnStopMyService,btnBindMyService,btnUnbindMyService,btnExit; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnStartMyService=(Button)this.findViewById(R.id.btnStartMyService); btnStartMyService.setOnClickListener(new ClickEvent()); btnStopMyService=(Button)this.findViewById(R.id.btnStopMyService); btnStopMyService.setOnClickListener(new ClickEvent()); btnBindMyService=(Button)this.findViewById(R.id.btnBindMyService); btnBindMyService.setOnClickListener(new ClickEvent()); btnUnbindMyService=(Button)this.findViewById(R.id.btnUnbindMyService); btnUnbindMyService.setOnClickListener(new ClickEvent()); btnExit=(Button)this.findViewById(R.id.btnExit); btnExit.setOnClickListener(new ClickEvent()); } @Override public void onDestroy() { super.onDestroy(); Log.e("Activity","onDestroy"); } private ServiceConnection _connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName arg0, IBinder arg1) { } @Override public void onServiceDisconnected(ComponentName name) { } }; class ClickEvent implements View.OnClickListener{ @Override public void onClick(View v) { Intent intent=new Intent(testService.this,MyService.class); if(v==btnStartMyService){ testService.this.startService(intent); } else if(v==btnStopMyService){ testService.this.stopService(intent); } else if(v==btnBindMyService){ testService.this.bindService(intent, _connection, Service.BIND_AUTO_CREATE); } else if(v==btnUnbindMyService){ if(MyService.ServiceState=="onBind")//Service綁定了之後才能解綁 testService.this.unbindService(_connection); } else if(v==btnExit) { testService.this.finish(); } } } }
MyService.java:
package com.testService; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class MyService extends Service { static public String ServiceState=""; @Override public IBinder onBind(Intent arg0) { Log.e("Service", "onBind"); ServiceState="onBind"; return null; } @Override public boolean onUnbind(Intent intent){ super.onUnbind(intent); Log.e("Service", "onUnbind"); ServiceState="onUnbind"; return false; } @Override public void onCreate(){ super.onCreate(); Log.e("Service", "onCreate"); ServiceState="onCreate"; } @Override public void onDestroy(){ super.onDestroy(); Log.e("Service", "onDestroy"); ServiceState="onDestroy"; } @Override public void onStart(Intent intent,int startid){ super.onStart(intent, startid); Log.e("Service", "onStart"); ServiceState="onStart"; } }
把每個回呼都打上 log,跑一遍就能直觀看到狀態如何流轉。選 startService 還是 bindService,取決於你希望 Service 的生命週期跟誰綁在一起。
仿 360 手機衛士的 Android 實作思路解析
專案背景這個練習以仿手機安全衛士為主題,目的不是複製商業產品,而是把 Android 常見元件、服務、廣播、資料庫、自訂 View 與動畫整合成一個完整的小專案。對初學者
Android 仿今日頭條下拉導航選單實作解析
在移動端新聞應用裡,頂部的頻道導航是常見設計。用戶點擊標題區域後,下方展開一個可選擇的頻道面板,既能提升可讀性,也能讓首屏保持簡潔。本文以仿今日頭條的下拉導航為例,說明如
Android Native 層 Binder.transact() 呼叫 onTransact() 失敗分析
在 Native 層使用 Binder 進行跨進程溝通時,若 transact() 沒有如預期觸發對方的 onTransact(),通常不是單一 API 問題,而是 Bi
Android 自訂圓形按鈕:點擊時顯示進度
先來看看效果: 這其實是一個託管在 GitHub 上的開源控制項——一個圓形的按鈕 View,同時能顯示進度。 使用方式很簡單:把專案從 GitHub 下載下來匯入