編輯:關於 Android 程式設計
Service 是 Android 四大元件裡跟 Activity 個性最接近的一個:有自己的生命週期,創建與配置方式幾乎一致,同樣繼承自 Context,所以 getResources()、getContentResolver() 這些方法都能用。差別只在於它沒有華麗的介面,長期在後台默默做事。
先熟悉生命週期回呼:
IBinder onBind(Intent):必須實作,回傳的 IBinder 是外部與 Service 通訊的橋樑。void onCreate():第一次創建時立刻回呼。int onStartCommand(Intent, int, int):每次呼叫 startService() 都會回呼(早期版本是 onStart)。void onDestroy():Service 被關閉之前回呼。boolean onUnbind(Intent):所有綁定的客戶端都斷線時回呼。public class MyService extends Service {
public static final String TAG = MyService.class.getSimpleName();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.v(TAG, "onCreate() executed");
Log.v(TAG, "MyService thread id is " + Thread.currentThread().getId());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand() executed");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.v(TAG, "onDestroy() executed");
}
}
註冊方式與 Activity 幾乎相同,只是標籤換成 service:
<service android:name=".MyService" />
這種啟動方式下,呼叫者與 Service 之間沒有羈絆,Activity 關掉了 Service 依然運行。
case R.id.start_service:
startService(new Intent(this, MyService.class));
break;
case R.id.stop_service:
stopService(new Intent(this, MyService.class));
break;
先按 Start Service 再按 Stop Service,log 如下:
不關閉服務的情況下連按三次 Start Service:
由此可以驗證一個關鍵結論:onCreate() 只在 Service 第一次被創建時回呼一次,之後無論呼叫多少次 startService,它都不會再執行;但 onStartCommand() 每次啟動都會執行。
這種方式下 Service 與呼叫者綁在一起,呼叫者退出,Service 隨之終止,而且雙向通訊成為可能。先改造 MyService,透過 onBind 把 Binder 交出去:
public class MyService extends Service {
public static final String TAG = MyService.class.getSimpleName();
private MyBinder mBinder = new MyBinder();
@Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "onBind() executed");
return mBinder;
}
// onCreate / onStartCommand / onDestroy 同上
class MyBinder extends Binder {
public void startDownload() {
Log.v(TAG, "startDownload() executed");
}
}
}
bindService 的三個參數:
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myBinder = (MyBinder) service;
myBinder.startDownload(); // 透過 Binder 直接呼叫 Service 的方法
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.v(TAG, "onServiceDisconnected() " + name);
}
};
case R.id.bind_service:
bindService(new Intent(this, MyService.class), connection, BIND_AUTO_CREATE);
break;
case R.id.unbind_service:
unbindService(connection);
break;
按 Bind Service 再按 unBind Service 的結果:
可以看到 MainActivity 已成功呼叫到 MyService 的 startDownload(),通訊建立。
當你呼叫 bindService 把兩者綁定後,MyService 的 onBind() 所回傳的 IBinder 會被系統送進 MainActivity 的 onServiceConnected(ComponentName name, IBinder service) 的 service 參數。之後 Activity 只要轉型成自訂的 Binder 子類,就能直接呼叫 Service 暴露的方法。這也是 AIDL 跨進程通訊的基礎縮影。
用 startService 啟動會走 onStartCommand,用 bindService 啟動卻不會。原因是兩種方式下 Service 的生命週期路徑不同:前者是 onCreate → onStartCommand → onDestroy;後者是 onCreate → onBind → onUnbind → onDestroy。兩者可以混用,此時 Service 會一直存活到 stopService 與所有 unbind 都發生為止。
另外提醒:Service 預設跑在呼叫它的主進程主線程上,onCreate() 或 onStartCommand() 裡寫耗時邏輯一樣會 ANR。需要真正卸重,請自己開線程,或直接用 IntentService / JobIntentService。
Android 源碼解析:View 的 Touch 事件分發機制
Touch 事件分發是 Android 面試與實戰中的高頻考點,網上解析文章也很多。本文的側重在於「用實驗現象反推源碼」——先動手跑出日誌順序,再回到原始碼中找出支撐這些
Android 平台關於時間與日期的相關類和方法(Date/Time)
本文致力於把日期與時間相關的類和方法整理列出,以備查閱參考,因此文章將持續更新。 1. Time 類 這個類可以取得具體的日期/時間以及時區,並能在日期/時間格式與字串及
Android 自定義 DragGridView:長按拖拽與數據交換
在一些需要自定義排序的頁面中,用戶可能希望通過長按拖拽來調整 item 順序。實現這種效果,可以基於 GridView 進行擴展,結合長按監聽、WindowManager
Lumia手機也能暢讀電子書:WiFi傳書實作
Lumia看電子書可用Anyview閱讀的WiFi傳書。開啟軟體選擇點我導書、WiFi傳書,取得IP位址後,在PC瀏覽器輸入並上傳txt檔。 手機與PC需在同一Wi-Fi