public interface HttpDownloader { public void setDownloadManager(HttpDownloadManager manager); public HttpDownloadManager getDownloadManager(); public void executeAction(); }
public class MyAsyncTask extends AsyncTask<String, Void, Bitmap> implements HttpDownloader{ private HttpDownloadManager httpDownloadManager; protected Bitmap doInBackground(String... params) { httpDownloadManager.downloadStarted(); ... } protected void onPostExecute(Bitmap bitmap) { httpDownloadManager.downloadCompleted(); ... } public void setDownloadManager(HttpDownloadManager httpDownloadManager){ this.httpDownloadManager = httpDownloadManager; } public HttpDownloadManager getDownloadManager(){ return httpDownloadManager } public void executeAction(){ this.execute(); } }
public class HttpDownloadManager{ private LinkedList<HttpDownloader> tasks = new LinkedList<HttpDownloader>(); private int mMaxTaskNumber = 1; private int mActiveTaskNumber = 0; private boolean isRunning = false; private ExectorService mService = Executors.newSingleThreadExecutor(); public HttpDownloadManager() { } public void addTask(HttpDownloader task) { try{ task.setDownloadManager(this); tasks.offer(task); } catch (Exception e) { e.printStackTrace(); } if (!isRunning && !mService.isShutdown()) { mService.submit(new DoTask()); } } public void deleteTasks() { tasks.clear(); } public void destroy() { if (!mService.isShutdown) { mService.shutdown(); } } public final void setMaxTaskNumber(int maxTaskNumber) { mMaxTaskNumber = maxTaskNumber; } public void downloadStarted() { mActiveTaskNumber++; } public void downloadCompleted() { mActiveTaskNumber--; } public boolean isAvailable() { if (mActiveTaskNumber <= mMaxTaskNumber) { return true; } else { return false; } } private class DoTask implements Runnable { public void run() { isRunning = true; while(!tasks.isEmpty()) { if (HttpDownloadManager.this.isAvailable()) { HttpDownloader task = tasks.poll(); task.executeAction(); } } isRunning = false; } } }
Android之下载管理者
时间: 2024-10-11 04:06:55