文章連結 : 點我
平常要使用Android Service , 要了解甚麼是bind , 如何呼叫Service
但Intent Service不需要知道那麼多 , 只要會使用Intent與接收Intent就
可以運作 , 超級方便 , 連Android Framework中都有使用此種Service
加速與簡化程式碼
Intent Service是使用StartService的方式啟動 , 如同Start Service作法
屬於Local Service , 外界不能使用
Intent Service是使用StartService的方式啟動 , 如同Start Service作法
屬於Local Service , 外界不能使用
IntentService是非同步的呼叫 , 那要怎麼回傳資料呢?
可以使用CallBack
1.Intent Service維護Listener list
2.Intent Service定義interface
public interface Listener {
public void onServiceCompleted(Intent callbackIntent);
}
3.Intent Service取得MainHandler ()
mMainHandler = new Handler(Looper.getMainLooper());
4.Acitivty實作Intent Service的interface並取得static版本的registerCallBack funtion將Activity Ref設定給Intent Service的Listener List
5.Activity使用Intent呼叫Service , 並將回呼的Intent(Activity與Action)放入extra中
Intent serviceIntent = new Intent(
context, ContactSaveService.class);
serviceIntent.setAction(ContactSaveService.ACTION_SAVE_CONTACT);
serviceIntent.putExtra(EXTRA_CONTACT_STATE, (Parcelable) state);
callbackIntent.putExtra(saveModeExtraKey, saveMode);
callbackIntent.setAction(callbackAction);
serviceIntent.putExtra(ContactSaveService.EXTRA_CALLBACK_INTENT, callbackIntent);
6.取出Call back Intent
Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
7.Intent Service呼叫Listener
mMainHandler.post(new Runnable() {
public void run() {
listener.onServiceCompleted(callbackIntent);
}
});
沒有留言:
張貼留言