編輯:關於 Android 程式設計
大多數 Service 場景並不需要同時處理多個請求——畢竟那是一個相當危險的多執行緒情境。如果你的服務就是這種「一次處理一件、做完就好」的型別,那麼繼承 IntentService 會比直接寫 Service 輕扶手很多。
所以我們要做的只有兩件事:實作 onHandleIntent(),以及——這點常被遺忘——必須提供建構子並呼叫 super(String),因為工作執行緒需要一個名稱。
public class HelloIntentService extends IntentService {
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public HelloIntentService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns,
* IntentService stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// 正常情況下這裡會做一些實際工作,例如下載檔案
long endTime = System.currentTimeMillis() + 5*1000;
while (System.currentTimeMillis() < endTime) {
synchronized (this) {
try {
wait(endTime - System.currentTimeMillis());
} catch (Exception e) { }
}
}
}
}
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1); // ← 處理完就自己停
}
}
public IntentService(String name) {
super();
mName = name;
}
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
protected abstract void onHandleIntent(Intent intent);
}
第一,停止時機在 ServiceHandler 裡。handleMessage() 先呼叫 onHandleIntent(),回來後立刻 stopSelf(msg.arg1),所以外部完全不必再呼叫。
第二,onHandleIntent() 是抽象方法。這就是為什麼你只要覆寫它就足夠了——IntentService 把執行緒建立、佇列排程、生命週期收尾都實作完了,只留這一個方法給子類填。
第三,onCreate() 用 HandlerThread 是一切的基礎。它建立一條帶 Looper 的工作執行緒,再把 mServiceLooper 交給 ServiceHandler,於是 onStart() 收到的每個 Intent 都會被包成 Message 排入佇列,單線程依序消化。
第四,setIntentRedelivery() 決定重試語意。設為 true 時 onStartCommand() 回傳 START_REDELIVER_INTENT,行程若在 onHandleIntent() 返回前被殺掉,系統會重啟服務並重新投遞(多個 Intent 中只有最後一個保證被重投);設為 false(預設)則回傳 START_NOT_STICKY,行程死了 Intent 就跟著消失。
實務上的取捨很清楚:需要併發處理多個請求、或需要與 UI 雙向溝通,就該用 Service 搭配自己的執行緒;只是單純把非同步任務丟進背景佇列,IntentService 就綽綽有餘,而且不容易寫錯。
Android 入門:Button 點擊事件與 Toast 提示控件綜合實戰
前面我們已經在 main.xml 裡定義了 Button 物件,接下來就來看看 Button 如何實現事件響應。 Button 按鈕觸發的事件處理,我們稱之為 Even
Android ListView 局部刷新:避免 notifyDataSetChanged 的進度條更新方案
ListView 的刷新機制是 Android 開發中的常見主題。一般做法是在資料變更後呼叫 notifyDataSetChanged,讓 ListView 重新繪製。但
深入 Android Handler:用消息佇列實作執行緒間通信 ITC
Handler 是操作執行緒內部消息佇列的類。正因為它能操作佇列,也就順帶成為執行緒間通信(ITC,Inter Thread Communication)的手段——這種方
Android 選項選單用法解析
選項選單基本概念 Android 的選單大致可分為選項選單、上下文選單與子選單。當 Activity 在前景執行時,使用者按下 Menu 鍵,即可開啟選項選單。 建立選項