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;
        }
    }
}

 

Android之下载管理者,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。