編輯:關於 Android 程式設計
A service is an application component that can perform long-running operations in the background and does not provide a user interface。通常 Service 用來執行一些耗時操作,或在後台執行不提供使用者互動介面的工作。其他應用組件可以啟動 Service,即便使用者切換到其他應用,啟動的 Service 仍可在後台運行。一個組件可與 Service 綁定並與之互動,甚至跨進程通信(IPC)。例如,Service 可在後台執行網路請求、播放音樂、進行檔案讀寫或與 ContentProvider 互動等。
要建立 Service,需繼承 Service 類別並重寫其回調方法,這些回調反映了 Service 的生命週期並提供了綁定機制。最重要的回調如下:
onStartCommand()若某組件以 startService() 啟動 Service(系統回調 onStartCommand()),則直到手動呼叫 stopSelf() 或 stopService() 才會停止。若某組件以 bindService() 綁定 Service(系統不回調 onStartCommand()),則只要處於綁定狀態 Service 就一直運行,解除綁定後即被 destroy。
當系統記憶體低時會強制停止 Service;若 Service 綁定了正在與使用者互動的 Activity,則較不易被 kill;前台 Service 幾乎不會被 kill。否則長時間在後台運行的 Service 會被降低優先級而容易被 kill,因此開發時應讓 Service 易於 restart,這取決於 onStartCommand() 的回傳值。該方法必須回傳一個整數,共有四種:
START_STICKY在 manifest 中註冊 Service 的方式如下:
此外,在 <service> 標籤中還可設定其他屬性:
android:name → 服務全限定類名(唯一不可缺省);android:label → 服務名稱,不設則預設為類名;android:icon → 服務圖示;android:permission → 宣告此服務的權限;android:process → 表示是否運行在另一進程;android:enabled → 設為 true 時預設被系統啟動;android:exported → 表示是否能被其他應用控制或連接。若不確定要啟動哪個 Service,可在 <service> 中設定 intent-filter,並在 Intent 中呼叫 setPackage() 方法為啟動的 Service 消除歧義。setPackage() 傳入一個代表包名的 String,表示該 Intent 只能在該包名下尋找符合條件的組件,傳入 null 則可在任意包下尋找。
啟動 Service 有兩種方式:Context.startService() 與 Context.bindService()。Service 也可同時在兩種方式下運行,這涉及 onStartCommand() 與 onBind() 兩個回調。無論以何種方式啟動,任何組件(甚至其他應用的組件)都可使用 Service 並透過 Intent 傳遞參數;也可在 manifest 中將 Service 設為私有,不允許其他應用存取。
其他組件呼叫 startService() 啟動 Service,一旦啟動即持續在後台運行,即便啟動它的組件已被 destroy。被 start 的 Service 通常在後台執行獨立操作,完成後應自行停止。建立 start Service 一般有兩種方式:
繼承 Service 類別:請務必在 Service 中開啟執行緒執行耗時操作,因為 Service 運行在主線程中。 繼承 IntentService 類別:若 Service 不需同時處理多個請求,使用 IntentService 是最佳選擇,只需重寫 onHandleIntent(),它預設開啟子線程,完成後會自動呼叫 stopSelf()。(1)繼承 Service 類別
若需在 Service 中執行多執行緒而非處理單一請求隊列,則需繼承 Service,分別處理每個 Intent,並為每個請求開啟執行緒:
public class MyService extends Service { private HandlerThread mThread; private Handler mHandler; @Override public void onCreate() { super.onCreate(); MainActivity.showlog("onCreate()"); initBackThread(); } private void initBackThread() { mThread = new HandlerThread("ServiceStartArguments"); mThread.start(); mHandler = new Handler(mThread.getLooper()) { @Override public void handleMessage(Message msg) { //模擬耗時線程操作 MainActivity.showlog("processing...msg.arg1="+msg.arg1); try { Thread.sleep(5000); } catch (Exception e) { Thread.currentThread().interrupt(); } MainActivity.showlog("stopSelf...msg.arg1="+msg.arg1); //當所有操作完成後,服務自己停止 stopSelf(msg.arg1); } }; } @Override public int onStartCommand(Intent intent, int flags, int startId) { MainActivity.showlog("onStartCommand()"); Message msg = mHandler.obtainMessage(); msg.arg1 = startId; mHandler.sendMessage(msg); return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); MainActivity.showlog("onDestroy()"); } @Override public IBinder onBind(Intent intent) { MainActivity.showlog("onBind()"); return null; } }
添加 Button 點擊事件:
@Override public void onClick(View v) { switch (v.getId()) { case R.id.start_service: showlog("click Start Service button"); Intent it1 = new Intent(this, MyService.class); startService(it1); break; case R.id.stop_service: showlog("click Stop Service button"); Intent it2 = new Intent(this, MyService.class); stopService(it2); break; default: break; } }
運行後點擊 Start Service,流程為:點擊 → onCreate → onStartCommand → 耗時事件處理(5S)→ onDestroy。若連續點擊兩次 Start Service,則第一次為 onCreate → onStartCommand → 耗時處理(5S),第二次為 onStartCommand → 耗時處理(5S)→ onDestroy;兩次耗時處理在同一線程,依序執行。點擊 Start Service 後再點擊 Stop Service 即可立即停止。



注:多次啟動請求可能導致 onStartCommand() 多次呼叫,但只需呼叫一次 stopSelf() 即可停止所有請求。
(2)繼承 IntentService 類別
大多數情況下 start Service 不會同時處理多個請求,且多執行緒較危險,因此繼承 IntentService 是不錯選擇。使用要點:預設在子線程處理 Intent;在 onHandleIntent() 中處理依時間排序的 Intent 隊列,無須擔心多執行緒問題;所有請求完成後自動停止,無須手動呼叫 stopSelf();預設實作 onBind() 並回傳 null;預設實作 onStartCommand() 並將 Intent 以序列形式交給 onHandleIntent()。
public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override public void onHandleIntent(Intent intent) { //模擬耗時線程操作 MainActivity.showlog("processing..."); try { Thread.sleep(5000); } catch (Exception e) { Thread.currentThread().interrupt(); } } }
若需在 IntentService 的繼承類中重寫 onCreate()、onStartCommand() 或 onDestroy(),請先呼叫各自的父類方法以保證子線程正常啟動。例如 onStartCommand() 需回傳父類方法:
@Override public int onStartCommand(Intent intent, int flags, int startId) { MainActivity.showlog("onStartCommand()"); return super.onStartCommand(intent, flags, startId); }
注:除 onHandleIntent() 外,onBind() 也無須呼叫父類方法。
bindService() 的意思是把 Service 與呼叫它的客戶類綁起來,若客戶類被銷毀,Service 也會被銷毀。其好處是執行後 Service 會回調 onBind(),可從此回傳一個實作 IBinder 介面的類別,客戶端操作該類別即可與 Service 通信,例如取得 Service 運行狀態。若 Service 尚未運行,以此方法啟動只會呼叫 onCreate() 而不呼叫 onStartCommand()。
觀察 MyService 會發現 onBind() 尚未使用,它正是用於與 Activity 建立關聯。以下重新撰寫 MyBindService:
public class MyBindService extends Service { private MyBinder mBinder = new MyBinder(); @Override public void onCreate() { super.onCreate(); MainActivity.showlog("onCreate()"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { MainActivity.showlog("onStartCommand()"); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); MainActivity.showlog("onDestroy()"); } //Service自定義方法 public void doSomethingInService(){ MainActivity.showlog("doSomethingInService()"); } //復寫onBind方法,並且返回IBinder的實現類 @Override public IBinder onBind(Intent intent) { MainActivity.showlog("onBind()"); return mBinder; } @Override public boolean onUnbind(Intent intent) { MainActivity.showlog("onUnbind()"); return super.onUnbind(intent); } //內部類,擴展自Binder類 class MyBinder extends Binder { //MyBinder自定義方法 public void doSomethingInBinder() { MainActivity.showlog("doSomethingInBinder()"); } public MyBindService getService(){ return MyBindService.this; } } }
這裡新增了一個繼承自 Binder 的 MyBinder 類別,並在其中加入 doSomethingInBinder() 方法以在後台執行任務;Service 中另有 doSomethingInService() 方法同樣可執行後台任務。接著修改 MainActivity 讓兩者建立關聯:
public class MainActivity extends Activity implements OnClickListener { private Button startService; private Button stopService; private Button startIntentService; private Button stopIntentService; private Button bindService; private Button unbindService; private MyBindService.MyBinder myBinder; private boolean isConnected = false; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { showlog("onServiceDisconnected"); isConnected = false; } @Override public void onServiceConnected(ComponentName name, IBinder iBinder) { showlog("onServiceConnected"); myBinder = (MyBindService.MyBinder) iBinder; myBinder.doSomethingInBinder(); MyBindService service = myBinder.getService(); service.doSomethingInService(); isConnected = true; } }; @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); startIntentService = (Button) findViewById(R.id.start_intent_service); stopIntentService = (Button) findViewById(R.id.stop_intent_service); bindService = (Button) findViewById(R.id.bind_service); unbindService = (Button) findViewById(R.id.unbind_service); startService.setOnClickListener(this); stopService.setOnClickListener(this); startIntentService.setOnClickListener(this); stopIntentService.setOnClickListener(this); bindService.setOnClickListener(this); unbindService.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.start_service: showlog("click Start Service button"); Intent it1 = new Intent(this, MyService.class); startService(it1); break; case R.id.stop_service: showlog("click Stop Service button"); Intent it2 = new Intent(this, MyService.class); stopService(it2); break; case R.id.start_intent_service: showlog("click Start IntentService button"); Intent it3 = new Intent(this, MyIntentService.class); startService(it3); break; case R.id.stop_intent_service: showlog("click Stop IntentService button"); Intent it4 = new Intent(this, MyIntentService.class); stopService(it4); break; case R.id.bind_service: showlog("click Bind Service button"); Intent it5 = new Intent(this, MyBindService.class); bindService(it5, connection, BIND_AUTO_CREATE); break; case R.id.unbind_service: showlog("click Unbind Service button"); if(isConnected == true){ unbindService(connection); } break; default: break; } } public static void showlog(String info) { System.out.print("Watson "+info+"\n"); } }
這裡先建立了一個 ServiceConnection 匿名類,重寫 onServiceConnected() 與 onServiceDisconnected(),兩者分別在 Activity 與 Service 建立及解除關聯時呼叫。在 onServiceConnected() 中透過向下轉型取得 MyBinder 實例,此後 Activity 即可依場景呼叫 MyBinder 中的任何 public 方法,實現「Activity 指揮 Service」的功能。真正建立關聯是在 Bind Service 按鈕的點擊事件中,透過 bindService() 完成。該方法接收三個參數:Intent 物件、ServiceConnection 實例與標志位(BIND_DEBUG_UNBIND 用於調試,BIND_AUTO_CREATE 為預設),此處傳入 BIND_AUTO_CREATE 表示建立關聯後自動建立 Service,會執行 onCreate() 但不執行 onStartCommand()。


由於綁定時指定 BIND_AUTO_CREATE,點擊 Bind Service 時 Service 也會被建立,此時點擊 Unbind Service 解除關聯即可銷毀。需注意,任何 Service 在整個應用範圍內都是通用的,MyService 不僅可與 MainActivity 建立關聯,也可與任何其他 Activity 建立關聯,且都能取得相同的 MyBinder 實例。
銷毀方式:startService → stopService;bindService → unbindService。需注意幾點:(1)呼叫 bindService 綁定後應在某處呼叫 unbindService 解除綁定(雖然 Activity finish 時會自動解除並停止);(2)使用 startService 後一定要以 stopService 停止,不管是否使用 bindService;(3)同時使用兩者時,Service 的終止需 unbindService 與 stopService 同時呼叫,無論呼叫順序如何,需兩者都執行後才會停止;(4)旋轉螢幕時,Activity 會重新建立,先前 bindService 建立的連接會斷開;(5)多次呼叫 unbindService 釋放相同連接會拋出異常,因此可建立一個 boolean 變數判斷是否已呼叫過。
對於 StartService 啟動的服務,Service 本身還提供 stopSelf 讓自己停止。若系統正在處理多個 onStartCommand() 請求,可呼叫 stopSelf(int) 以確保停止的是最新的啟動請求——傳入的 ID 代表啟動請求(會傳遞至 onStartCommand()),若呼叫前收到新的 Start 請求,ID 無法匹配則 Service 不會停止。
... private void initBackThread() { mThread = new HandlerThread("ServiceStartArguments"); mThread.start(); mHandler = new Handler(mThread.getLooper()) { @Override public void handleMessage(Message msg) { //線程操作 MainActivity.showlog("processing...msg.arg1="+msg.arg1); try { Thread.sleep(5000); } catch (Exception e) { Thread.currentThread().interrupt(); } MainActivity.showlog("stopSelf...msg.arg1="+msg.arg1); stopSelf(msg.arg1); } }; } @Override public int onStartCommand(Intent intent, int flags, int startId) { MainActivity.showlog("onStartCommand()"); Message msg = mHandler.obtainMessage(); msg.arg1 = startId; mHandler.sendMessage(msg); return START_STICKY; } ...
Thread 用於開啟子線程執行耗時操作而不阻塞主線程。而 Service 常被誤解為用來處理後台任務,但事實上 Service 運行在主線程裡。在 MainActivity 的 onCreate() 中加入打印目前線程 id 的 Log:
showlog("MainActivity thread id is " + Thread.currentThread().getId());
同時在 MyService 的 onCreate() 中加入:
MainActivity.showlog("MyService thread id is " + Thread.currentThread().getId());
重新運行並點擊 Start Service,會發現兩者的線程 id 完全相同,由此證明 Service 確實運行在主線程,若在 Service 中編寫非常耗時的程式碼,程式也會出現 ANR。

詳細說明:
Thread:Thread 是程式執行的最小單位,是分配 CPU 的基本單位,可用來執行非同步操作。 Service:Service 是 Android 的一種機制,若為 Local Service,則運行在主進程的 main 線程上(如 onCreate、onStart 都在 main 線程被呼叫);若為 Remote Service,則運行在獨立進程的 main 線程上。因此請不要把 Service 理解成線程。Android 的「後台」是指其運行完全不依賴 UI,即使 Activity 被銷毀或程式關閉,只要進程還在,Service 就可繼續運行,例如需要與伺服器保持心跳連線的應用。既然 Service 運行在主線程,長時間執行心跳會阻塞主線程,但可在 Service 中再建立子線程處理耗時邏輯。相較於在 Activity 中建立子線程(Activity 銷毀後難以重新取得該子線程實例,且其他 Activity 無法操作),Service 則可讓所有 Activity 建立關聯並操作其中的方法,即使 Activity 銷毀後重新關聯仍能取得原有 Binder 實例。此外還可在 Service 中註冊 BroadcastReceiver,透過發送 broadcast 控制它,這些都是 Thread 做不到的。一個較標準的 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 被 destroy 後狀態欄顯示才消失。有些專案因特殊需求必須使用前台 Service,例如墨跡天氣在後台更新天氣資料的同時會在狀態欄顯示當前天氣。

建立前台 Service 並不複雜,修改 MyService 的 onCreate():
@Override public void onCreate() { super.onCreate(); MainActivity.showlog("onCreate()"); initBackThread(); Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new Notification.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setWhen(System.currentTimeMillis()) .setTicker("有通知到來") .setContentTitle("這是通知的標題") .setContentText("這是通知的內容") .setOngoing(true) .setContentIntent(pendingIntent) .build(); /*使用startForeground,如果id為0,那麼notification將不會顯示*/ startForeground(1, notification); }
這裡建立了一個 Notification 物件並設定其配置與資料,設定點擊通知後開啟 MainActivity,然後呼叫 startForeground() 讓 MyService 變成前台 Service 並顯示通知圖示。重新運行並點擊 Start Service 或 Bind Service,就會以前台模式啟動,並在狀態欄彈出通欄圖示。

可呼叫 stopForeground(Boolean bool) 移除前台 Service,該方法傳入 boolean 變數表示是否一併清除狀態欄的 notification,但它並不停止 Service;若停止正在前台運行的 Service,notification 也會一併被清除。
最後看進程的分類:
前台進程 Foreground process:目前使用者操作的 Activity 所在進程、綁定了目前使用者操作 Activity 的 Service 所在進程、呼叫了 startForeground() 的 Service,典型場景為後台播放音樂。 可見進程 Visible process:處於暫停狀態的 Activity、綁定到暫停狀態 Activity 的 Service。 服務進程 Service process:透過 startService() 啟動的 Service。 後台進程 Background process:處於停止狀態的 Activity。 空進程 Empty process。
Android實現圖片中疊加可拖動文字功能
本文為大家分享一個在圖片中疊加文字、並支持拖動改變位置的實例,供感興趣的讀者參考。 之所以做這個Demo,是因為項目裡遇到一個頗為奇葩的需求:用戶拍照後分享到微信,同時希
Android 數據存儲之 SQLite:SQLiteOpenHelper 與 SQLiteDatabase 實戰
SQLite 是一種輕量級的嵌入式關系型數據庫,.db 文件多用於手機端。 其中 SQLiteOpenHelper 負責創建、打開、更新與關閉數據庫,並承擔創建數據表的職
Android APK 動態加載機制研究(二):資源訪問與 Activity 生命週期管理
前言 上一篇我們分析了 Android 中 APK 動態加載的基本原理,並在結尾指出兩個尚未解決的難題:資源的訪問與 Activity 生命週期管理。本文接著處理這兩件事
Android 開發實戰:手把手打造屬於你的 ButterKnife 框架(二)
一、建立專案與 processor 模組 新增 module 時務必選擇 Java Library,否則後續會找不到 AbstractProcessor。接著在 app