編輯:Android 開發實例
上一篇講了 Activity 與 Intent,這次換 Service。如果把 Activity 當成前台程式,那 Service 就是沒有介面的後台程式,整個生命週期都在背後執行。它和 Activity 一樣由 Intent 驅動,參數也靠 Intent 傳遞。
要在專案裡新增一個 Service,兩步:先寫一個繼承 Service 的類別,再到 AndroidManifest.xml → Application → 新增 <service> 標籤把它登記進去。少了第二步,startService() 會直接丟出 ActivityNotFoundException。
兩者都能啟動 Service,真正的差別是生命週期的歸屬:
stopService() 明確結束。若只在 Activity 裡 start 卻沒 stop,會出現「畫面關掉了、Service 還在跑」的情況,白白耗電。unbindService() 解開;即使不解,當 Activity 走到 onDestroy() 時,系統也會自動幫你解綁並回收。一句話記法:需要「按鈕按下去後持續在背景做事」,用 startService;需要「Activity 與 Service 之間雙向溝通、跟著畫面存亡」,用 bindService。
觀察生命週期最直接的方式,就是在每個回呼裡打 log。這支 Service 另外用一個靜態變數 ServiceState 記住目前狀態,方便 Activity 查詢(例如解綁前先確認是否處於 onBind)。
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 void onCreate() {
super.onCreate();
Log.e("Service", "onCreate");
ServiceState = "onCreate";
}
@Override
public void onStart(Intent intent, int startid) {
super.onStart(intent, startid);
Log.e("Service", "onStart");
ServiceState = "onStart";
}
@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 onDestroy() {
super.onDestroy();
Log.e("Service", "onDestroy");
ServiceState = "onDestroy";
}
}
觀察 log 的順序,可以歸納出兩條不同的路徑:startService 走的是 onCreate → onStart →(stopService)→ onDestroy;bindService 走的是 onCreate → onBind →(unbindService)→ onUnbind → onDestroy。
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") { // 綁定之後才能解綁
testService.this.unbindService(_connection);
}
} else if (v == btnExit) {
testService.this.finish();
}
}
}
}
要留意 bindService 的第三個參數 BIND_AUTO_CREATE:它表示目標 Service 不存在時順手把它建起來。如果傳 0,Service 只會在已經活著時才綁得上。另外 ServiceConnection 的兩個回呼裡通常會拿到 IBinder——那才是呼叫 Service 公開方法的入口;範例中 Service 的 onBind() 回傳 null,所以只示範了生命週期,沒有跨元件呼叫。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button android:id="@+id/btnStartMyService"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="StartMyService" />
<Button android:id="@+id/btnStopMyService"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="StopMyService" />
<Button android:id="@+id/btnBindMyService"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="BindMyService" />
<Button android:id="@+id/btnUnbindMyService"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="UnbindMyService" />
<Button android:id="@+id/btnExit"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="退出程序" />
</LinearLayout>
這是本篇最值得記住的實驗:startService 之後呼叫 Activity.finish(),Service 完全不為所動,繼續在背景跑到你 stop 它為止;而 bindService 之後 finish,Service 會在 onDestroy 時被動地走完 onUnbind → onDestroy。理解這一點,就不會寫出「使用者退出 App 後音樂還在無限播放」這種 bug。
值得說明的是,這套 API 在後續版本有幾個重要變化:onStart() 已被 onStartCommand() 取代;從 Android 8.0 起,背景執行有嚴格的分段限制,長時間的常駐工作應該改用 Foreground Service(必須顯示常駐通知)或 WorkManager;而 bindService 這種模式至今仍然是 Activity 與 Service 雙向通訊的正統做法,搭配 LocalBinder 取得 Service 實例即可直接呼叫其方法。
用 Gallery 打造 3D 立體相冊:Android 手把手實作(附效果圖)
做過客製開機畫面功能的人應該都遇過這個需求:使用者要先從一堆圖片裡挑一張當開機畫面,所以應用層必須提供一個「能瀏覽、能挑選」的圖片選擇器。與其自己從零打造,不如拿系統既有
Android ScrollView 嵌套 ScrollView 的解法與原理
Android 有一條眾所周知的限制:同一方向的兩個 ScrollView 不能直接嵌套。但需求常常不是由懂平台規則的人提出的,所以問題最後還是落到開發者頭上。 好消息是
Android 登入畫面從零實作:完整程式碼與流程驗證
登入畫面是所有需要帳號的 App 的第一道門。它要處理的事情比看起來多:輸入欄的型別設定、點擊事件的綁定、字串比對、錯誤提示,還有一個常被省略的安全設計——限制連續嘗試次
Android 補間動畫入門:縮放、旋轉與淡入淡出一次學會
Android 上的動畫方案不少,其中最簡單也最廣泛使用的莫過於補間動畫(Tween Animation)。你只需要給定起始值、結束值、尺寸、時間長度、旋轉角度等參數,系