編輯:關於 Android 程式設計
Service 常被形容為「沒有界面的 Activity」。這個比喻抓到了重點——它同樣有生命週期、同樣要在 Manifest 註冊——但兩者在啟動方式與通訊能力上有關鍵差異,而這差異決定了你該用哪一個。
Service 沒有使用者介面,不與使用者直接互動,因此通常執行在後台,適合不需要畫面的資料處理、長時間下載、音樂播放等工作。開發只需兩步:定義一個繼承 Service 的子類,並在 AndroidManifest.xml 中註冊。
回想啟動 Activity 有 startActivity 與 startActivityForResult 兩種;Service 同樣有兩種:
startService(Intent); bindService(Intent service, ServiceConnection conn, int flags);
差異在於能否與啟動者互動,這一點直接決定了取回資料的能力。
public class BindService extends Service {
private int count;
private boolean quit;
// 定義 onBind 方法所回傳的物件
private MyBinder binder = new MyBinder();
// 透過繼承 Binder 來實作 IBinder
public class MyBinder extends Binder {
public int getCount() {
return count; // 取得 Service 的運行狀態
}
}
// 必須實作的方法
@Override
public IBinder onBind(Intent intent) {
System.out.println("Service is Binded");
return binder;
}
// Service 被建立時回呼
@Override
public void onCreate() {
super.onCreate();
System.out.println("Service is Created");
// 啟動一條執行緒,動態修改 count
new Thread() {
@Override
public void run() {
while (!quit) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
count++;
}
}
}.start();
}
// Service 被中斷連線時回呼
@Override
public boolean onUnbind(Intent intent) {
System.out.println("Service is Unbinded");
return true;
}
// Service 被關閉之前回呼
@Override
public void onDestroy() {
super.onDestroy();
this.quit = true;
System.out.println("Service is Destroyed");
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
this.quit = true;
System.out.println("Service is ReBinded");
}
}
這個 Service 做的事很簡單:開一條執行緒,每 1000 毫秒把 count 加一,並透過 binder 物件把 count 交給外界讀取。
public class MainActivity extends Activity {
Button startService_bnt, bindService_bnt;
// 保存所啟動 Service 的 IBinder 物件
BindService.MyBinder binder;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService_bnt = (Button) findViewById(R.id.start_bnt);
bindService_bnt = (Button) findViewById(R.id.bind_bnt);
// 建立啟動 Service 的 Intent
Intent intent = new Intent(this, BindService.class);
startService_bnt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View source) {
startService(intent);
}
});
bindService_bnt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View source) {
bindService(intent, conn, Service.BIND_AUTO_CREATE);
Toast.makeText(MainActivity.this,
"Service 的 count 值為:" + binder.getCount(), 4000).show();
}
});
}
// 定義 ServiceConnection 物件
private ServiceConnection conn = new ServiceConnection() {
// 與 Service 連線成功時回呼
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("--Service Connected--");
// 取得 Service 的 onBind 方法所回傳的 MyBinder 物件
binder = (BindService.MyBinder) service;
}
// 與 Service 斷開連線時回呼
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("--Service Disconnected--");
}
};
}
startService(intent) 啟動的 Service 不具備與啟動者交互的能力,就像 startActivity 無法從新開啟的 Activity 取回結果一樣。Service 會 independently 運行直到自己 stopSelf 或被人 stopService。
bindService() 則不同,啟動者能從 Service 取回資料。關鍵在第二個參數 conn:它是一個 ServiceConnection 物件,連線成功時系統會回呼 onServiceConnected(),而這個方法的 IBinder service 參數就是 Service 對外暴露的物件。拿到它,就能呼叫 Service 提供的任何公開方法。
所以資料交互的管道是 IBinder,而不是 Intent——這點與 Activity 之間傳值的方式截然不同。
很多人卡在這一行:
binder = (BindService.MyBinder) service;
明明 onBind 回傳的是 IBinder,為什麼要轉成 MyBinder?而且回傳的 binder 上並沒有 count 這個欄位,為什麼呼叫 binder.getCount() 就能拿到值?
答案在 Service 端這段:
public class MyBinder extends Binder {
public int getCount() {
return count;
}
}
Binder 是 IBinder 的實作類,MyBinder 繼承 Binder 並自行加上 getCount 方法。onBind 回傳的雖然宣告為 IBinder,實際物件就是 MyBinder 實例,因此轉型之後就能存取 getCount。IBinder 介面本身沒有任何業務方法,getCount 是 MyBinder 幫它補上的——這也是為什麼必須轉型才能呼叫。
使用 bindService 時,ServiceConnection 的註冊與 unbindService 必須成對,否則連線不會釋放。另外範例中 Service 自己開了裸 Thread,正式專案更合適的做法是改用 IntentService 或 JobIntentService,讓系統代為管理執行緒生命週期。而從 Android 8.0 開始,後台啟動 Service 受到嚴格限制,長時間的後台工作應改用 WorkManager 或前景 Service。
Android 垂直跑馬燈升級:加入圖片內容
原本只支援文字舊版垂直跑馬燈多半只針對 TextView 設計,若需求變成圖文並用,就需要調整原本元件。可將項目視圖改為包含 ImageView 與 TextView 的
自定義 GifView:在 Android 上播放 GIF 動畫
GIF 在網頁開發裡隨處可見,很多動畫效果不必再寫程式碼就能呈現,App 中的使用也越來越多。但 Android SDK 並沒有現成的 GifView,因此只能自己打造一
AlertDialog.Builder 圖解實戰:七種常見對話框一次搞定
做專案時難免要用到各種對話框。多數平台的 API 只給幾個最陽春的版本,於是很多人第一反應是繼承 Dialog 自己改寫一個。這條路可行,但若這個對話框只在一個地方用到,
Android 複選框 CheckBox 元件用法詳解
首先,我們在版面配置檔中註冊 CheckBox。 activity_main.xml MainActivity.java CheckBox 有兩種常用的