編輯:關於 Android 程式設計
Service 是 Android 四大組件之一(Activity、Service、BroadcastReceiver、ContentProvider),地位與 Activity 相當,但它沒有介面、無法自己跑到前台,只能默默待在背景執行,同時又能與其他組件互動。
它特別適合那些「使用者離開了畫面,工作卻必須繼續」的場景:
一句話總結:Service 永遠藏在背後替使用者做事。
啟動 Service 有兩種方式:
context.startService()context.bindService()context.startService() -> onCreate() -> onStart() -> Service running -> context.stopService() -> onDestroy() -> Service stop
呼叫方式:
startService(new Intent(LoginActivity.this, XXService.class));
行為細節:
onCreate(),接著呼叫 onStart();onStart(),因此 onStart() 在一個 Service 生命週期內可能被呼叫多次;stopService(),Service 會一直在背景執行,直到下一次啟動它的組件呼叫 stopService() 才會結束。所以 startService 的生命週期是:onCreate → onStart(可多次)→ onDestroy。
context.bindService() -> onCreate() -> onBind() -> Service running -> onUnbind() -> onDestroy() -> Service stop
onBind() 會回傳一個 IBinder 介面給呼叫端,讓呼叫端能直接回呼 Service 的方法,例如取得 Service 實例、查詢執行狀態或下達指令。此時呼叫者(通常是 Activity)就與 Service 綁在一起了,呼叫者銷毀時,Service 會依序走 onUnbind() → onDestroy() 退出。
所以 bindService 的生命週期是:onCreate → onBind(僅一次)→ onUnbind → onDestroy。
Service 的生命週期比 Activity 單純許多,核心只有三個方法:onCreate()、onStart()、onDestroy()。
第一次啟動時依序觸發 onCreate() 與 onStart();停止時執行 onDestroy()。特別注意:如果 Service 已經在跑,再次啟動時不會重複執行 onCreate(),而是直接跳到 onStart()。
Service 可以透過 stopSelf() 或 stopSelfResult() 自行結束;外部則只要呼叫一次 stopService(),無論前面啟動過多少次,都會一次停下來。

下面用一個最經典的例子把整個流程串起來:Activity 負責操作介面,Service 負責真正播放音樂,兩者透過 Intent 傳遞指令碼溝通。
PlayMusicService(Activity 端)
public class PlayMusicService extends Activity implements OnClickListener {
private Button playBtn, stopBtn, pauseBtn, exitBtn, closeBtn;
private Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music_service);
playBtn = (Button) findViewById(R.id.play);
stopBtn = (Button) findViewById(R.id.stop);
pauseBtn = (Button) findViewById(R.id.pause);
exitBtn = (Button) findViewById(R.id.exit);
closeBtn = (Button) findViewById(R.id.close);
playBtn.setOnClickListener(this);
stopBtn.setOnClickListener(this);
pauseBtn.setOnClickListener(this);
exitBtn.setOnClickListener(this);
closeBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int op = -1;
intent = new Intent("com.homer.service.musicService");
switch (v.getId()) {
case R.id.play: op = 1; break; // 播放
case R.id.stop: op = 2; break; // 停止
case R.id.pause: op = 3; break; // 暫停
case R.id.close: this.finish(); break; // 只關畫面
case R.id.exit: // 關畫面 + 停服務
op = 4;
stopService(intent);
this.finish();
break;
}
Bundle bundle = new Bundle();
bundle.putInt("op", op);
intent.putExtras(bundle);
startService(intent);
}
@Override
public void onDestroy() {
super.onDestroy();
if (intent != null) {
stopService(intent);
}
}
}
MusicService(Service 端)
public class MusicService extends Service {
private static final String TAG = "MyService";
private MediaPlayer mediaPlayer;
@Override
public IBinder onBind(Intent arg0) {
return null; // 只用 startService,不需要提供 binder
}
@Override
public void onCreate() {
Log.v(TAG, "onCreate");
Toast.makeText(this, "show media player", Toast.LENGTH_SHORT).show();
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(this, R.raw.tmp);
mediaPlayer.setLooping(false);
}
}
@Override
public void onStart(Intent intent, int startId) {
Log.v(TAG, "onStart");
if (intent != null) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
int op = bundle.getInt("op");
switch (op) {
case 1: play(); break;
case 2: stop(); break;
case 3: pause(); break;
}
}
}
}
public void play() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
public void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
try {
// stop 之後若要再次 start,必須先 prepare
mediaPlayer.prepare();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
@Override
public void onDestroy() {
Log.v(TAG, "onDestroy");
Toast.makeText(this, "stop media player", Toast.LENGTH_SHORT).show();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
AndroidManifest.xml 註冊
<activity
android:name=".service.PlayMusicService"
android:label="@string/app_name" />
<service
android:name=".service.MusicService"
android:enabled="true">
<intent-filter>
<action android:name="com.homer.service.musicService" />
</intent-filter>
</service>
1. Activity 如何下達指令
Activity 端把各種操作抽象成數字(1 播放、2 停止、3 暫停),透過 Bundle 塞進 Intent 再送給 Service。這裡 Intent 的 action 字串 com.homer.service.musicService 必須與 Manifest 中 Service 的 <intent-filter> 一致,否則找不到目標。
2. Service 如何響應
Service 收到 startService(intent) 後,依序走 onCreate → onStart(可多次)→ onDestroy:
onCreate():建立 MediaPlayer 實例;onStart():用 intent.getExtras() 取出 op 並執行對應的播放動作;onDestroy():停止並 release() 音樂資源。3. close 與 exit 的差別(很常被忽略)
兩者都會關掉 Activity 視窗,但結果完全不同:
this.finish(),Service 並沒有被關掉,音樂會繼續在背景播放;stopService(intent) 讓 Service 走到 onDestroy() 釋放資源,這才 finish() 關掉視窗。這個差異正好說明了 Service 的核心價值:它的生命週期與 Activity 是獨立的。
Android 會盡可能讓應用進程活得久一點,但記憶體吃緊時勢必得淘汰一部分。系統的判斷依據是「重要性等級」,共五級,越前面越不容易被殺:
1. 前台進程(Foreground)
只要符合下列任一條件即屬之:正在與使用者互動、控制著使用者正在使用的基本服務、有 Service 正在執行生命週期回呼(如 onCreate()、onStart()、onDestroy())、或有 BroadcastReceiver 正在執行 onReceive()。這類進程是系統最後才會動用的手段。
2. 可見進程(Visible)
沒有前台組件,但仍影響使用者所看到的畫面。例如一個非前台但仍可見的 Activity(onPause() 已被呼叫,例如半透明的對話框式 Activity),或服務於此 Activity 的 Service。
3. 服務進程(Service)
透過 startService() 啟動、且不屬於前兩類。使用者雖然看不到它,但它確實在使用者關心的範圍內(背景播放音樂、背景下載)。系統會優先保住它們。
4. 背景進程(Background)
非 Currently running 的 Activity(onStop() 已被呼叫)。這類進程數量通常很多,系統用 LRU(最近最少使用)清單管理,最久沒用到的會先被回收。只要 Activity 正確實作了生命週期並保存狀態,被回收不影響使用者體驗。
5. 空進程(Empty)
沒有任何活躍組件,留著只是為了加速下次啟動。系統會經常清掉它以平衡整體資源。
補充兩個實務結論:
這也解釋了一個常見設計取捨:當 Activity 需要執行長時間任務時,與其開一條背景執行緒(Activity 一死,執行緒的優先級也跟著掉),不如啟動一個 Service,讓這段工作至少能享有 Service 進程的優先級保障。
Android 仿余額寶數字滾動動畫實作
余額寶那種金額數字從 0 快速滾動到最終值的動畫,視覺效果很好,實作起來卻不難。以下是一個可直接複用的自訂 TextView。 效果預覽 完整程式碼 package
Android 開發者入門指南(一):從零開始到開發環境建置
適合誰閱讀 這篇指南適合初次接觸 Java 或 Android 的讀者,尤其是希望系統性建立基礎、卻不知道從哪裡開始的人。若你已經具備部分基礎,也可以依照目錄快速補齊環境
Android WindowManager解析與原理實踐(附Window機制完整梳理)
近來在網上看到有人提交了一個有趣的案例:應用可以開啟一個後台Service,偵測當前頂部應用,若為QQ或相關應用,就彈出一個自定義Window來誘騙使用者輸入帳號密碼。這
自定義 View 系列(5):99.99% 還原 QQ 側滑刪除效果
首先聲明,本文是在 GitHub 上「baoyongzhang」的 SwipeMenuListView 基礎上修改而來。 項目地址:https://github.com/