I wrote a lazy image downloader for my app using an ExecutorService. It gives me great control about how many downloads are running in parallel at what time and so on.
You can do it in two or three simple steps:
Create a LifoBlockingDeque class:
public class LifoBlockingDeque extends LinkedBlockingDeque {
@Override
public boolean offer(E e) {
// Override to put objects at the front of the list
return super.offerFirst(e);
}
@Override
public boolean offer(E e,long timeout, TimeUnit unit) throws InterruptedException {
// Override to put objects at the front of the list
return super.offerFirst(e,timeout, unit);
}
@Override
public boolean add(E e) {
// Override to put objects at the front of the list
return super.offerFirst(e);
}
@Override
public void put(E e) throws InterruptedException {
//Override to put objects at the front of the list
super.putFirst(e);
}
}
Create the executor:
mThreadPool = new ThreadPoolExecutor(THREAD_POOL_SIZE,
THREAD_POOL_SIZE, 0L,
TimeUnit.MILLISECONDS,
new LifoBlockingDeque());
LinkedBlockingDeque is supported only from API Level 9. To use it on earlier versions do the following:
Use the Java 1.6 implementation - download it from here.
Then change
implements BlockingDeque
to
implements BlockingQueue
To make it compile on Android. BlockingDeque is subtype of BlockingQueue, so no harm done.
And you're done!