編輯:關於 Android 程式設計
Service 是 Android 四大組件之一,它沒有界面,卻承擔著在後台持續工作的責任。它由 Activity 或其他 Context 啟動,可以在用戶離開應用之後繼續運行——比如音樂播放、文件下載、定位上報。
Intent intent = new Intent(ActivityA.this, ServiceA.class); startService(intent);
回調順序是 onCreate → onStartCommand → onDestroy。
這裡有個必須警惕的陷阱:如果只調用 startService 而沒有在合適的時機調用 stopService 或 stopSelf,Service 會一直駐留在後台運行,用戶退出應用也停不下來。這不僅浪費電量和內存,也容易招致系統或用戶的「殺進程」行為。
如果 Service 尚未啟動,回調順序是 onCreate → onDestroy(注意這裡走的是 onBind 而非 onStartCommand)。如果 Service 已經啟動,Activity 綁定時不會再次觸發 onCreate。無論哪種情況,Activity 退出前必須調用 unbindService 解綁,否則會拋出洩漏異常。
下面這個 Service 通過內部 Binder 類把自身實例暴露給綁定方,从而实现「Activity 直接調用 Service 方法」的能力:
public class ServiceA extends Service {
@Override
public void onCreate() {
Toast.makeText(this, "Service onCreate", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return new LocalBinder();
}
/** 內部 Binder:把 Service 實例交給綁定方 */
public class LocalBinder extends Binder {
public ServiceA getService() {
return ServiceA.this;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Received start id " + startId + ": " + intent,
Toast.LENGTH_SHORT).show();
// START_STICKY:Service 被系統回收後會嘗試重建
return START_STICKY;
}
@Override
public void onDestroy() {
Toast.makeText(this, "Service onDestory", Toast.LENGTH_SHORT).show();
}
/** 供外部調用的業務方法 */
public void doSomething() {
Toast.makeText(this, "Service do something", Toast.LENGTH_SHORT).show();
}
}
onStartCommand() 的返回值值得單獨說一下:START_STICKY 表示進程被殺後系統會重建 Service 但 Intent 為空;START_NOT_STICKY 表示不重建;START_REDELIVER_INTENT 則會重建並重新投遞最後一個 Intent,適合下載這類不能丟任務的場景。
package com.example.servicetest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button bindServiceBtn;
private Button unbindServiceBtn;
private boolean mIsBound = false;
private ServiceA mBoundService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
bindServiceBtn = (Button) findViewById(R.id.button_bindservice);
bindServiceBtn.setOnClickListener(this);
unbindServiceBtn = (Button) findViewById(R.id.button_unbindservice);
unbindServiceBtn.setOnClickListener(this);
unbindServiceBtn.setEnabled(false); // 未綁定時禁用解綁按鈕
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_bindservice:
doBindService();
break;
case R.id.button_unbindservice:
doUnbindService();
break;
}
}
/** ServiceConnection 是綁定狀態的觀察者 */
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
Toast.makeText(MainActivity.this, "This service connected",
Toast.LENGTH_SHORT).show();
// 連接建立後,把 IBinder 轉成具體類型即可直接調用 Service 方法
// 因為是我們自己進程內顯式綁定的 Service,轉型是安全的
mBoundService = ((ServiceA.LocalBinder) service).getService();
if (mBoundService != null) {
mBoundService.doSomething();
}
}
public void onServiceDisconnected(ComponentName className) {
// 進程崩潰等意外斷連時回調;同進程內一般不會出現
mBoundService = null;
Toast.makeText(MainActivity.this,
"This service disconnected unexpectedly",
Toast.LENGTH_SHORT).show();
unbindServiceBtn.setEnabled(false);
}
};
void doBindService() {
Toast.makeText(MainActivity.this, "Begin to bind a service.",
Toast.LENGTH_SHORT).show();
// BIND_AUTO_CREATE:Service 不存在時自動創建
bindService(new Intent(MainActivity.this, ServiceA.class),
mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
unbindServiceBtn.setEnabled(true);
}
void doUnbindService() {
if (mIsBound) {
Toast.makeText(MainActivity.this, "Begin to unbind a service.",
Toast.LENGTH_SHORT).show();
unbindService(mConnection);
mIsBound = false;
unbindServiceBtn.setEnabled(false);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// 兜底:Activity 銷燬時順手停掉 Service
stopService(new Intent(MainActivity.this, ServiceA.class));
}
}
只顧跑任務、不需要交互,用 startService,並且在任務結束時調用 stopSelf 主動收工。
需要頻繁雙向調用,用 bindService,通過 LocalBinder 拿到 Service 實例直接調方法,比通過 Intent 傳遞消息自然得多。
兩者兼備也很常見:先 startService 保證 Service 不被輕易回收,再 bindService 建立通信通道,並在退出時同時 stopService 與 unbindService。
別忘了主線程問題。Service 默認運行在應用的主線程裡,它並不等於「子線程」。耗時操作必須自己開線程,或者使用 IntentService(已在新版本中被 WorkManager 取代)來避免 ANR。
從 Android 8.0 開始,後台啟動限制收緊,直接 startService 在應用退到後台時會拋出 IllegalStateException,此時應改用 startForegroundService() 並在 5 秒內調用 startForeground() 顯示通知。長時間任務更推薦交給 WorkManager 或前台 Service 來承載。
Android AsyncTask 原始碼解析:執行流程、執行緒池與注意事項
AsyncTask 是 Android 早期常見的異步任務工具,讓開發者能在背景執行工作,並把結果回傳到 UI 執行緒。它本質上是 FutureTask 與 Handle
Android 仿 Win8 磁貼介面:自訂 MyImageView 的翻轉與縮放
本文要仿的是 Win8 那種一格一格的方塊介面,做法並不複雜,換掉圖片資源就能變成自己想要的樣子。 一、自訂 MyImageView 這個控制項根據手指按下的位置分兩
Android 自訂 Chronometer 實現簡訊驗證碼秒表倒計時功能
本文為大家分享透過 Chronometer 實現倒計時功能,Android 提供了實現按秒計時的 API,供各位參考,具體內容如下。一、自訂 ChronometerVie
Android 圖形渲染全路徑:從像素誕生到 SurfaceFlinger 合成上屏
在 UI 的畫圖流程中,我們先暫且不糾結「要畫的數據是怎麼填充的」,而是聚焦另一個問題:這些已經畫好的數據,究竟經歷了怎樣的旅程,最終抵達屏幕? 整條鏈路大致是:UI 獲