Tape 是一组跟队列相关的工具类,同时也适用于 Android 平台。
示例代码:
/** Listener for starting the upload service when the queue has tasks. */ public class ImageQueueServiceListener implements ObjectQueue.Listener<ImageUploadTask> { private final Context context; public ImageQueueServiceStarter(Context context) { this.context = context; } @Override public void onAdd(ObjectQueue<ImageUploadTask>, ImageUploadTask task) { context.startService(new Intent(context, ImageQueueService.class)); } @Override public void onRemove(ObjectQueue<ImageUploadTask>) {} } /** Service which iterates through pending upload tasks one-by-one. */ public class ImageQueueService extends Service implements ImageUploadTask.Callback { private TaskQueue<ImageUploadTask> queue; private boolean running; @Override public void onCreate() { super.onCreate(); // Obtain TaskQueue here (e.g., through injection) } @Override public int onStartCommand(Intent intent, int flags, int startId) { executeNext(); return START_STICKY; } public void executeNext() { if (running) return; // Only one task at a time. ImageUploadTask task = queue.peek(); if (task != null) { task.execute(this); running = true; return; } stopSelf(); // We're done for now. } @Override public void imageUploadComplete() { running = false; queue.remove(); executeNext(); } }