public final class DownloadThread extends Thread
{
private static final String TAG = DownloadThread.class.getSimpleName();
private Handler handler;
private int totalQueued;
private int totalCompleted;
private final DownloadThreadListener listener;
private boolean isRunning = false;
protected boolean isStop;
private TaskInitiator mtaskInitiator = null;
/**
* @return the isRunning
*/
public boolean isRunning()
{
return isRunning;
}
public DownloadThread(DownloadThreadListener listener)
{
this.listener = listener;
isStop = false;
}
@Override
public void run()
{
try
{
Looper.prepare();
mtaskInitiator = new TaskInitiator();
handler = new Handler();
isRunning = true;
Looper.loop();
}
catch (Throwable t)
{
Log.e(TAG, "DownloadThread halted due to an error", t);
}
}
public synchronized void requestStop()
{
isStop = true;
}
public synchronized void enqueueDownload(DownloadTask task)
{
mtaskInitiator = new TaskInitiator();
mtaskInitiator.setTask(task);
handler.post(mtaskInitiator);
totalQueued++;
}
public synchronized void removeTasks()
{
if (mtaskInitiator != null)
{
handler.removeCallbacks(mtaskInitiator);
totalQueued = 0;
totalCompleted = 0;
}
}
class TaskInitiator implements Runnable
{
private DownloadTask task = null;
public DownloadTask getTask()
{
return task;
}
public void setTask(DownloadTask task)
{
this.task = task;
}
public TaskInitiator()
{
// TODO Auto-generated constructor stub
}
@Override
public void run()
{
try
{
task.run();
}
finally
{
if (isStop)
{
Looper.myLooper().quit();
}
synchronized (DownloadThread.this)
{
signalUpdate(task.getCurrentBitmap(), task.getCurrentFeedUrl());
task.setCurrentBitmap(null);
totalCompleted++;
}
}
}
}
public synchronized int getTotalQueued()
{
return totalQueued;
}
public synchronized int getTotalCompleted()
{
return totalCompleted;
}
public void signalUpdate(Bitmap bmap, String bmapUrl)
{
if (listener != null)
{
listener.handleDownloadThreadUpdate(bmap, bmapUrl);
}
}
}
并让您的 Activity 组件实现以下接口以从 Thread 类进行回调。
public interface DownloadThreadListener {
void handleDownloadThreadUpdate(Bitmap bmap,String bmapUrl);
Map<String, Bitmap> giveImages_Map();
ConcurrentHashMap<String, SoftReference<Bitmap>> giveSoftImages_Map();
}