首页 > 代码库 > Android之下载管理者
Android之下载管理者
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; } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。