Android xutils 分析修改 下載進度更新頻率

來源:互聯網
上載者:User

Android xutils 分析修改 下載進度更新頻率


因為在更新進度的時候,有點卡,所以想,減緩進度更新的間隔時間。使其不那麼頻繁。

直接看程式碼分析下。

HttpHandler.java 實現了RequestCallBackHandler的下載進度監聽


 private ResponseInfo handleResponse(HttpResponse response) throws HttpException, IOException {        if (response == null) {            throw new HttpException("response is null");        }        if (isCancelled()) return null;        StatusLine status = response.getStatusLine();        int statusCode = status.getStatusCode();        if (statusCode < 300) {            Object result = null;            HttpEntity entity = response.getEntity();            if (entity != null) {                isUploading = false;                if (isDownloadingFile) {                    autoResume = autoResume && OtherUtils.isSupportRange(response);                    String responseFileName = autoRename ? OtherUtils.getFileNameFromHttpResponse(response) : null;                    FileDownloadHandler downloadHandler = new FileDownloadHandler();                    result = downloadHandler.handleEntity(entity, this, fileSavePath, autoResume, responseFileName); //在這裡我找到了,進度介面實現的實體了,我們點進去看看。                } else {                    StringDownloadHandler downloadHandler = new StringDownloadHandler();                    result = downloadHandler.handleEntity(entity, this, charset);                    if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {                        HttpUtils.sHttpCache.put(requestUrl, (String) result, expiry);                    }                }            }            return new ResponseInfo(response, (T) result, false);        } else if (statusCode == 301 || statusCode == 302) {            if (httpRedirectHandler == null) {                httpRedirectHandler = new DefaultHttpRedirectHandler();            }            HttpRequestBase request = httpRedirectHandler.getDirectRequest(response);            if (request != null) {                return this.sendRequest(request);            }        } else if (statusCode == 416) {            throw new HttpException(statusCode, "maybe the file has downloaded completely");        } else {            throw new HttpException(statusCode, status.getReasonPhrase());        }        return null;    }

FileDownloadHandler.java裡面,xutils對進度的更新做了如下操作。

如果處於進度更新狀態,就讓其走間隔更新進度,其他狀態不進行間隔設定。

public class FileDownloadHandler {    public File handleEntity(HttpEntity entity,                             RequestCallBackHandler callBackHandler,                             String target,                             boolean isResume,                             String responseFileName) throws IOException {        if (entity == null || TextUtils.isEmpty(target)) {            return null;        }        File targetFile = new File(target);        if (!targetFile.exists()) {            File dir = targetFile.getParentFile();            if (dir.exists() || dir.mkdirs()) {                targetFile.createNewFile();            }        }        long current = 0;        BufferedInputStream bis = null;        BufferedOutputStream bos = null;        try {            FileOutputStream fileOutputStream = null;            if (isResume) {                current = targetFile.length();                fileOutputStream = new FileOutputStream(target, true);            } else {                fileOutputStream = new FileOutputStream(target);            }            long total = entity.getContentLength() + current;            bis = new BufferedInputStream(entity.getContent());            bos = new BufferedOutputStream(fileOutputStream);            if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {                return targetFile;            }            byte[] tmp = new byte[4096];            int len;            while ((len = bis.read(tmp)) != -1) {                bos.write(tmp, 0, len);                current += len;                if (callBackHandler != null) {                    if (!callBackHandler.updateProgress(total, current, false)) {  //進度更新,有更新的頻率                        return targetFile;                    }                }            }            bos.flush();            if (callBackHandler != null) {                callBackHandler.updateProgress(total, current, true);//必須更新            }        } finally {            IOUtils.closeQuietly(bis);            IOUtils.closeQuietly(bos);        }        if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {            File newFile = new File(targetFile.getParent(), responseFileName);            while (newFile.exists()) {                newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName);            }            return targetFile.renameTo(newFile) ? newFile : targetFile;        } else {            return targetFile;        }    }}



最後,我們回到HttpHandler.java裡面

    private long lastUpdateTime;    @Override    public boolean updateProgress(long total, long current, boolean forceUpdateUI) {        if (callback != null && this.state != State.CANCELLED) {            if (forceUpdateUI) {                this.publishProgress(UPDATE_LOADING, total, current);             } else {                long currTime = SystemClock.uptimeMillis();                if (currTime - lastUpdateTime >= callback.getRate()) {                    lastUpdateTime = currTime;                    this.publishProgress(UPDATE_LOADING, total, current); //間隔一定時間進行更新 進度                }            }        }        return this.state != State.CANCELLED;    }


最後,到哪裡設定呢。間隔時間呢。

到RequestCallBack.java



private static final int DEFAULT_RATE = 1000;


private static final int MIN_RATE = 200;

//修改這裡即可。完畢

public final int getRate() {
if (rate < MIN_RATE) {
return MIN_RATE;
}
return rate;
}

或者通過在 callback裡面去 setRate(2000)都可以。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.