編輯:關於 Android 程式設計
在 Android 的四大組件之中,Service 扮演著「幕後推手」的角色。它是一個不具備使用者介面的應用元件,專門負責在背景執行長時間的操作。當某個應用元件啟動了 Service,即使使用者切換到其他 App,它依然會在背景持續運行。此外,其他元件也能透過綁定的方式與 Service 互動,甚至實現跨行程通訊(IPC)。舉例來說,處理網路交易、播放音樂、讀寫檔案或與內容提供者溝通,這些工作都可以交由 Service 在背景默默完成。
從使用方式來看,Service 主要可以歸納為「啟動型」與「綁定型」兩種。
當應用元件(例如 Activity)呼叫 startService() 時,Service 便進入「已啟動」狀態。一旦啟動,它就能在背景無限期地運行下去,即便啟動它的元件已經被銷毀也無妨。這類 Service 通常負責執行單一操作,且不會將結果回傳給呼叫者,例如在網路上下載或上傳檔案。任務完成後,Service 應該自行停止。
當應用元件呼叫 bindService() 與 Service 建立連線時,Service 便進入「已綁定」狀態。綁定型 Service 提供了一個用戶端—伺服器介面,允許元件與它互動、發送請求、取得結果,甚至能透過跨行程通訊(IPC)來運作。這類 Service 只在有元件綁定在它身上時才會存活,且可同時接受多個元件綁定;但當所有元件都解除綁定後,Service 便會被銷毀。
重要提醒:Service 預設運行在它所屬行程的主執行緒(Main Thread)中,它本身不會建立獨立執行緒,也不會跑在另一個行程裡(除非你另行指定)。這代表著,如果你的 Service 需要執行 CPU 密集型或阻塞式的工作(例如播放 MP3、進行網路連線),你應該在 Service 內部另開一條新執行緒來處理。透過獨立執行緒,能有效降低「應用程式無回應」(ANR)錯誤的風險,同時讓主執行緒專心處理與使用者的互動。
Service 生命週期示意圖:

public class DemoService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
//必須要重寫的方法
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
//開啟服務
public void click1(View view) {
Intent intent = new Intent(this,DemoService.class);
startService(intent);
}
//關閉服務
public void click2(View view) {
Intent intent = new Intent(this,DemoService.class);
stopService(intent);
}
... ...
關於 onCreate 與 onStartCommand:onCreate 只在 Service 第一次被建立時執行一次,之後重複啟動只會觸發 onStartCommand。服務一旦啟動便會長期運行,直到使用者手動停止為止。
核心目的:為了呼叫 Service 內部的方法。
//點擊按鈕 綁定服務 開啟服務的第二種方式
public void click3(View view) {
Intent intent = new Intent(this,DemoService.class);
//連接到demoservice 這個服務
conn = new Myconn();
bindService(intent, conn,BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
//當activity銷毀時要解綁服務
unbindService(conn);
super.onDestroy();
}
//定義一個類來監視服務的狀態
private class Myconn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
System.out.println("onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
System.out.println("onServiceDisconnected");
}
}
第一次點擊按鈕時,會執行 Service 的 onCreate 與 onBind 方法;當 onBind 回傳 null 時,onServiceConnected 不會被執行。第二次點擊 bind 時,Service 不會再有反應。以 bind 方式啟動的 Service,與 Activity 同生共死。
此外需注意:Service 不能重複解綁,重複解綁會拋出異常;以 bind 方式啟動的 Service 不會出現在系統設定裡,形同一個「隱形服務」。
BanZhengService.java
public class BanZhengService extends Service{
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public void banZheng(int money) {
if(money>1000){
Toast.makeText(getApplicationContext(),"我是領導 把證給你辦了",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"就這點錢 還想辦事...",Toast.LENGTH_LONG).show();
}
}
//定義中間人ibinder
public class MyBinder extends Binder {
public void callbanZheng(int money){
//調用辦證的方法
banZheng(money);
}
}
}
配置 service
MainActivity.java
public class MainActivity extends AppCompatActivity {
private MyConn conn;
private BanZhengService.MyBinder myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent= new Intent(this,BanZhengService.class);
conn = new MyConn();
bindService(intent,conn,BIND_AUTO_CREATE);
}
public void click(View view) {
myBinder.callbanZheng(100000);
}
@Override
protected void onDestroy() {
//解綁服務
unbindService(conn);
super.onDestroy();
}
//監視服務的狀態
public class MyConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
myBinder = (BanZhengService.MyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
}
重點在於 BanZhengService 中定義了「中間人」MyBinder,並在其中提供一個方法去呼叫 Service 內部的業務邏輯。

DemoService.java
public class DemoService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public void banZheng(int money) {
if (money > 1000) {
Toast.makeText(getApplicationContext(), "我是領導 把證給你辦了", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "就這點錢 還想辦事...", Toast.LENGTH_LONG).show();
}
}
public void playMajing() {
System.out.println("陪領導打麻將");
}
public void 洗桑拿() {
System.out.println("陪領導洗桑拿");
}
//定義中間人ibinder
public class MyBinder extends Binder implements Iservice {
public void callbanZheng(int money) {
//調用辦證的方法
banZheng(money);
}
public void callPlayMajing() {
playMajing();
}
public void callXiSanNa() {
洗桑拿();
}
}
}
Iservice.java
public interface Iservice {
//把領導想暴露的方法
public void callbanZheng(int money);
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private MyConn conn;
private Iservice myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, DemoService.class);
conn = new MyConn();
bindService(intent, conn, BIND_AUTO_CREATE);
}
public void click(View view) {
myBinder.callbanZheng(100000);
//只有領導才能調桑拿
//myBinder.callPlayMajing();
// myBinder.callXiSanNa();
}
@Override
protected void onDestroy() {
//解綁服務
unbindService(conn);
super.onDestroy();
}
//監視服務的狀態
private class MyConn implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
myBinder = (Iservice) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
}
Service 中的程式碼預設都運行在主執行緒,如果直接在其中處理耗時邏輯,很容易觸發 ANR(Application Not Responding)。這時候就需要導入多執行緒的技術——在 Service 的具體方法裡另開子執行緒來處理耗時工作。一個較為標準的寫法如下:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@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);
}
}
但這種寫法一旦啟動就會持續運行,必須呼叫 stopService() 或 stopSelf() 才能停止。若想讓服務在執行完畢後自動停止,可以這樣寫:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
// 處理具體的邏輯
stopSelf();
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
}
這樣的寫法雖然不複雜,但工程師往往容易忘記開啟執行緒,或忘記呼叫 stopSelf()。為了能簡單地建立一個「異步且會自動停止」的服務,Android 特別提供了 IntentService 類,完美解決了上述兩種尷尬。用法如下:
public class MyIntentService extends IntentService {
public MyIntentService() {
super("MyIntentService"); // 調用父類的有參構造函數
}
/* public MyIntentService(String name) {
super(name);
}*/
@Override
protected void onHandleIntent(Intent intent) {
// 打印當前線程的id
Log.d("MyIntentService", "Thread id is " + Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService", "onDestroy executed");
}
}
啟動 MyIntentService:
public void click5(View view) {
// 打印主線程的id
Log.d("MainActivity", "Thread id is " + Thread.currentThread(). getId());
Intent intentService = new Intent(this, MyIntentService.class);
startService(intentService);
}

從執行結果可以看到,MyIntentService 與 MainActivity 所在的執行緒 id 並不相同,而且 onDestroy() 也被執行了,說明 MyIntentService 在運行完畢後確實自動停止了。這正是集「開啟執行緒」與「自動停止」於一身的 IntentService。
我們知道,用 startService 開啟的服務會一直運行,除非自己呼叫 stopService;而 bindService 開啟的服務雖能呼叫其內部方法,生命週期卻與 Activity 綁定、同生共死。若想同時享有「長期運行」與「呼叫內部方法」兩大好處,就需要採用混合方式開啟服務。
開啟流程:
- 先呼叫 startService 啟動服務,讓它在背景長期運行
- 再呼叫 bindService 啟動服務,以取得中間人物件
關閉流程:
- 呼叫 unbindService 解綁服務
- 呼叫 stopService 關閉服務
MainActivity.java
public class MainActivity extends AppCompatActivity {
private IService iService;
private Myconn conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//混合開啟服務
//先調用startService 目的是可以保證服務在後台長期運行
Intent intent = new Intent(this,MusicService.class);
startService(intent);
//調用bindservice 目的是獲取我們定義的中jian人對象 就可以間接的調用服務
conn = new Myconn();
bindService(intent, conn,BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
//當activity銷毀的時候 解綁服務 不報紅色日志
unbindService(conn);
super.onDestroy();
}
public void click1(View view) {
//播放
iService.callplayMusic();
}
public void click2(View view) {
//暫停
iService.callpauseMusic();
}
public void click3(View view) {
//繼續播放
iService.callreplayMusic();
}
private class Myconn implements ServiceConnection {
//當服務連接成功
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//獲取我們定義的中間人Ibinder
iService = (IService) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
}
MusicService.java
public class MusicService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
//把我們定義的中間人返回
return new MyBinder();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/**
* 開啟一個線程,驗證後台服務是否一直運行
*/
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//要做的事情
Log.d("MusicService", new Date().toString());
//每隔十秒執行一次
handler.postDelayed(this, 10000);
}
};
//兩秒後執行
handler.postDelayed(runnable, 2000);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
public void playMusic() {
Toast.makeText(getApplication(), "音樂播放了", Toast.LENGTH_SHORT).show();
System.out.println("音樂播放了");
}
public void pauseMusic() {
Toast.makeText(getApplicationContext(), "音樂暫停了", Toast.LENGTH_SHORT).show();
System.out.println("音樂暫停了");
}
public void replayMusic() {
Toast.makeText(getApplicationContext(), "音樂繼續播放了", Toast.LENGTH_SHORT).show();
System.out.println("音樂繼續播放了");
}
//定義service和activity的中間人對象(Ibinder)
private class MyBinder extends Binder implements IService {
@Override
public void callplayMusic() {
playMusic();
}
@Override
public void callpauseMusic() {
pauseMusic();
}
@Override
public void callreplayMusic() {
replayMusic();
}
}
}
IService.java
public interface IService {
//在接口裡暴露方法
public void callplayMusic();
public void callpauseMusic();
public void callreplayMusic();
}
如此一來便能呼叫 Service 內的方法。即便關閉應用程式,仍會定時印出時間,證明 Service 還在背景運行——只要行程不關閉,它就會持續運作下去。
四大組件之間可以互相聯繫、共同為應用服務。當接收到特定廣播時,若有需要,就能啟動服務來執行相應操作,這也是開啟服務的一種方式。
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//把服務開啟
Intent intent1= new Intent(context,PhoneService.class);
context.startService(intent1);
System.out.println("開啟服務");
}
}
Android 進階必備:事件分發與攔截機制完整解析
一、Android 控制項架構 二、先給結論 (1)父 View 優先攔截當前事件,攔截不成才輪到子 View 攔截。(2)一旦攔截成功,系統會沿著「子 View
Android 適配器教程(二):用 SimpleCursorAdapter 把資料庫攤成列表
上一篇用 ArrayAdapter 建立了最基礎的列表,也說明了 Adapter 作為資料與視圖之間橋樑的本質。這篇接著在同一個 Demo 專案裡添第二個例子,主角是另一
Android 網路通訊入門:HttpURLConnection 與 HttpClient 實戰
在 Android 平台上發送 HTTP 請求,常見的做法有兩種:HttpURLConnection 與 HttpClient。本文將透過一個完整的範例,帶你分別掌握這兩
[Android] 拍照、裁剪、保存並顯示在 ImageView 中的完整實作
最近在做的 Android 專案有一部分涉及圖像處理。這裡先記錄如何調用系統 Camera 應用進行拍照,接著裁切、保存並顯示到 ImageView,過程中遇到的困難與解