我想實現一個基於簡單數字優先級處理意圖的IntentService(source code)。具有較高優先級的意圖應該首先由服務處理,而不是具有較低優先級的意向。Android中的優先隊列服務
Android上有什麼東西可以做到這一點嗎?如果沒有,關於如何實現它的任何指針?
我想實現一個基於簡單數字優先級處理意圖的IntentService(source code)。具有較高優先級的意圖應該首先由服務處理,而不是具有較低優先級的意向。Android中的優先隊列服務
Android上有什麼東西可以做到這一點嗎?如果沒有,關於如何實現它的任何指針?
基於CommonsWare的答案和Android的IntentService
source code第一次嘗試實施具有優先級的意圖服務。將進行廣泛測試並進行相應的編輯。
public abstract class PriorityIntentService extends Service {
private final class QueueItem implements Comparable<QueueItem> {
Intent intent;
int priority;
int startId;
@Override
public int compareTo(QueueItem another) {
if (this.priority < another.priority) {
return -1;
} else if (this.priority > another.priority) {
return 1;
} else {
return (this.startId < another.startId) ? -1 : 1;
}
}
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
try {
final QueueItem item = mQueue.take();
onHandleIntent(item.intent);
if (mQueue.isEmpty()) {
PriorityIntentService.this.stopSelf();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static final String EXTRA_PRIORITY = "priority";
private String mName;
private PriorityBlockingQueue<QueueItem> mQueue;
private boolean mRedelivery;
private volatile ServiceHandler mServiceHandler;
private volatile Looper mServiceLooper;
public PriorityIntentService(String name) {
super();
mName = name;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread("PriorityIntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
mQueue = new PriorityBlockingQueue<QueueItem>();
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
protected abstract void onHandleIntent(Intent intent);
@Override
public void onStart(Intent intent, int startId) {
final QueueItem item = new QueueItem();
item.intent = intent;
item.startId = startId;
final int priority = intent.getIntExtra(EXTRA_PRIORITY, 0);
item.priority = priority;
mQueue.add(item);
mServiceHandler.sendEmptyMessage(0);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
public void setIntentRedelivery(boolean enabled) {
mRedelivery = enabled;
}
}
不是。雖然沒有太多的IntentService
。在PriorityBlockingQueue
的支持下烹飪PriorityIntentService
,而不是Handler
+ Looper
,應該不會太長。
感謝CommonsWare。你介意添加一些僞代碼來指向正確的方向嗎?我想PriorityBlockingQueue應該存儲意圖,比較器應該區分不同的優先級。不過,不知道如何訂購同樣重要的意圖。 – hpique 2010-12-16 16:38:57
@hgpc:如果您沒有任何其他標準,請比較哈希碼或其他內容。 – CommonsWare 2010-12-16 16:43:01
@CommonsWare一個意圖是否有某種時間戳? – hpique 2010-12-16 16:45:48