use of org.xutils.common.Callback in project xUtils3 by wyouflf.
the class DownloadManager method startDownload.
public synchronized void startDownload(String url, String label, String savePath, boolean autoResume, boolean autoRename, DownloadViewHolder viewHolder) throws DbException {
String fileSavePath = new File(savePath).getAbsolutePath();
DownloadInfo downloadInfo = db.selector(DownloadInfo.class).where("label", "=", label).and("fileSavePath", "=", fileSavePath).findFirst();
if (downloadInfo != null) {
DownloadCallback callback = callbackMap.get(downloadInfo);
if (callback != null) {
if (viewHolder == null) {
viewHolder = new DefaultDownloadViewHolder(null, downloadInfo);
}
if (callback.switchViewHolder(viewHolder)) {
return;
} else {
callback.cancel();
}
}
}
// create download info
if (downloadInfo == null) {
downloadInfo = new DownloadInfo();
downloadInfo.setUrl(url);
downloadInfo.setAutoRename(autoRename);
downloadInfo.setAutoResume(autoResume);
downloadInfo.setLabel(label);
downloadInfo.setFileSavePath(fileSavePath);
db.saveBindingId(downloadInfo);
}
// start downloading
if (viewHolder == null) {
viewHolder = new DefaultDownloadViewHolder(null, downloadInfo);
} else {
viewHolder.update(downloadInfo);
}
DownloadCallback callback = new DownloadCallback(viewHolder);
callback.setDownloadManager(this);
callback.switchViewHolder(viewHolder);
RequestParams params = new RequestParams(url);
params.setAutoResume(downloadInfo.isAutoResume());
params.setAutoRename(downloadInfo.isAutoRename());
params.setSaveFilePath(downloadInfo.getFileSavePath());
params.setExecutor(executor);
params.setCancelFast(true);
Callback.Cancelable cancelable = x.http().get(params, callback);
callback.setCancelable(cancelable);
callbackMap.put(downloadInfo, callback);
if (downloadInfoList.contains(downloadInfo)) {
int index = downloadInfoList.indexOf(downloadInfo);
downloadInfoList.remove(downloadInfo);
downloadInfoList.add(index, downloadInfo);
} else {
downloadInfoList.add(downloadInfo);
}
}
use of org.xutils.common.Callback in project xUtils3 by wyouflf.
the class HttpFragment method onTest1Click.
/**
* 1. 方法必须私有限定,
* 2. 方法参数形式必须和type对应的Listener接口一致.
* 3. 注解参数value支持数组: value={id1, id2, id3}
* 4. 其它参数说明见{@link org.xutils.view.annotation.Event}类的说明.
**/
@Event(value = R.id.btn_test1, type = View.OnClickListener.class)
private void onTest1Click(View view) {
/**
* 自定义实体参数类请参考:
* 请求注解 {@link org.xutils.http.annotation.HttpRequest}
* 请求注解处理模板接口 {@link org.xutils.http.app.ParamsBuilder}
*
* 需要自定义类型作为callback的泛型时, 参考:
* 响应注解 {@link org.xutils.http.annotation.HttpResponse}
* 响应注解处理模板接口 {@link org.xutils.http.app.ResponseParser}
*
* 示例: 查看 org.xutils.sample.http 包里的代码
*/
BaiduParams params = new BaiduParams();
params.wd = "xUtils";
// 有上传文件时使用multipart表单, 否则上传原始文件流.
// params.setMultipart(true);
// 上传文件方式 1
// params.uploadFile = new File("/sdcard/test.txt");
// 上传文件方式 2
// params.addBodyParameter("uploadFile", new File("/sdcard/test.txt"));
Callback.Cancelable cancelable = x.http().get(params, /**
* 1. callback的泛型:
* callback参数默认支持的泛型类型参见{@link org.xutils.http.loader.LoaderFactory},
* 例如: 指定泛型为File则可实现文件下载, 使用params.setSaveFilePath(path)指定文件保存的全路径.
* 默认支持断点续传(采用了文件锁和尾端校验续传文件的一致性).
* 其他常用类型可以自己在LoaderFactory中注册,
* 也可以使用{@link org.xutils.http.annotation.HttpResponse}
* 将注解HttpResponse加到自定义返回值类型上, 实现自定义ResponseParser接口来统一转换.
* 如果返回值是json形式, 那么利用第三方的json工具将十分容易定义自己的ResponseParser.
* 如示例代码{@link org.xutils.sample.http.BaiduResponse}, 可直接使用BaiduResponse作为
* callback的泛型.
*
* @HttpResponse 注解 和 ResponseParser接口仅适合做json, xml等文本类型数据的解析,
* 如果需要其他数据类型的解析可参考:
* {@link org.xutils.http.loader.LoaderFactory}
* 和 {@link org.xutils.common.Callback.PrepareCallback}.
* LoaderFactory提供PrepareCallback第一个泛型参数类型的自动转换,
* 第二个泛型参数需要在prepare方法中实现.
* (LoaderFactory中已经默认提供了部分常用类型的转换实现, 其他类型需要自己注册.)
*
* 2. callback的组合:
* 可以用基类或接口组合个种类的Callback, 见{@link org.xutils.common.Callback}.
* 例如:
* a. 组合使用CacheCallback将使请求检测缓存或将结果存入缓存(仅GET请求生效).
* b. 组合使用PrepareCallback的prepare方法将为callback提供一次后台执行耗时任务的机会,
* 然后将结果给onCache或onSuccess.
* c. 组合使用ProgressCallback将提供进度回调.
* ...(可参考{@link org.xutils.image.ImageLoader}
* 或 示例代码中的 {@link org.xutils.sample.download.DownloadCallback})
*
* 3. 请求过程拦截或记录日志: 参考 {@link org.xutils.http.app.RequestTracker}
*
* 4. 请求Header获取: 参考 {@link org.xutils.http.app.RequestInterceptListener}
*
* 5. 其他(线程池, 超时, 重定向, 重试, 代理等): 参考 {@link org.xutils.http.RequestParams}
*
**/
new Callback.CommonCallback<List<BaiduResponse>>() {
@Override
public void onSuccess(List<BaiduResponse> result) {
Toast.makeText(x.app(), result.get(0).toString(), Toast.LENGTH_LONG).show();
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
if (ex instanceof HttpException) {
// 网络错误
HttpException httpEx = (HttpException) ex;
int responseCode = httpEx.getCode();
String responseMsg = httpEx.getMessage();
String errorResult = httpEx.getResult();
// ...
} else {
// 其他错误
// ...
}
}
@Override
public void onCancelled(CancelledException cex) {
Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
}
@Override
public void onFinished() {
}
});
// cancelable.cancel(); // 取消请求
}
use of org.xutils.common.Callback in project xUtils3 by wyouflf.
the class ImageLoader method doLoad.
/**
* load from Network or DiskCache
*
* @param view
* @param url
* @param options
* @param callback
*/
private Cancelable doLoad(ImageView view, String url, ImageOptions options, Callback.CommonCallback<Drawable> callback) {
this.viewRef = new WeakReference<ImageView>(view);
this.options = options;
this.key = new MemCacheKey(url, options);
this.callback = callback;
if (callback instanceof Callback.ProgressCallback) {
this.progressCallback = (Callback.ProgressCallback<Drawable>) callback;
}
if (callback instanceof Callback.PrepareCallback) {
this.prepareCallback = (Callback.PrepareCallback<File, Drawable>) callback;
}
if (callback instanceof Callback.CacheCallback) {
this.cacheCallback = (Callback.CacheCallback<Drawable>) callback;
}
// set loadingDrawable
Drawable loadingDrawable = null;
if (options.isForceLoadingDrawable()) {
loadingDrawable = options.getLoadingDrawable(view);
view.setScaleType(options.getPlaceholderScaleType());
view.setImageDrawable(new AsyncDrawable(this, loadingDrawable));
} else {
loadingDrawable = view.getDrawable();
view.setImageDrawable(new AsyncDrawable(this, loadingDrawable));
}
// request
RequestParams params = createRequestParams(url, options);
if (view instanceof FakeImageView) {
synchronized (FAKE_IMG_MAP) {
FAKE_IMG_MAP.put(url, (FakeImageView) view);
}
}
return cancelable = x.http().get(params, this);
}
use of org.xutils.common.Callback in project xUtils3 by wyouflf.
the class HttpTask method doBackground.
@Override
@SuppressWarnings("unchecked")
protected ResultType doBackground() throws Throwable {
if (this.isCancelled()) {
throw new Callback.CancelledException("cancelled before request");
}
// 初始化请求参数
ResultType result = null;
resolveLoadType();
request = createNewRequest();
checkDownloadTask();
// retry 初始化
boolean retry = true;
int retryCount = 0;
Throwable exception = null;
HttpRetryHandler retryHandler = this.params.getHttpRetryHandler();
if (retryHandler == null) {
retryHandler = new HttpRetryHandler();
}
retryHandler.setMaxRetryCount(this.params.getMaxRetryCount());
if (this.isCancelled()) {
throw new Callback.CancelledException("cancelled before request");
}
// 检查缓存
Object cacheResult = null;
if (cacheCallback != null && HttpMethod.permitsCache(params.getMethod())) {
// 尝试从缓存获取结果, 并为请求头加入缓存控制参数.
try {
clearRawResult();
LogUtil.d("load cache: " + this.request.getRequestUri());
rawResult = this.request.loadResultFromCache();
} catch (Throwable ex) {
LogUtil.w("load disk cache error", ex);
}
if (this.isCancelled()) {
clearRawResult();
throw new Callback.CancelledException("cancelled before request");
}
if (rawResult != null) {
if (prepareCallback != null) {
try {
cacheResult = prepareCallback.prepare(rawResult);
} catch (Throwable ex) {
cacheResult = null;
LogUtil.w("prepare disk cache error", ex);
} finally {
clearRawResult();
}
} else {
cacheResult = rawResult;
}
if (this.isCancelled()) {
throw new Callback.CancelledException("cancelled before request");
}
if (cacheResult != null) {
// 同步等待是否信任缓存
this.update(FLAG_CACHE, cacheResult);
synchronized (cacheLock) {
while (trustCache == null) {
try {
cacheLock.wait();
} catch (InterruptedException iex) {
throw new Callback.CancelledException("cancelled before request");
} catch (Throwable ignored) {
}
}
}
// 处理完成
if (trustCache) {
return null;
}
}
}
}
if (trustCache == null) {
trustCache = false;
}
if (cacheResult == null) {
this.request.clearCacheHeader();
}
// 判断请求的缓存策略
if (callback instanceof Callback.ProxyCacheCallback) {
if (((Callback.ProxyCacheCallback) callback).onlyCache()) {
return null;
}
}
// 发起请求
retry = true;
while (retry) {
retry = false;
try {
if (this.isCancelled()) {
throw new Callback.CancelledException("cancelled before request");
}
// 由loader发起请求, 拿到结果.
// retry 前关闭上次请求
this.request.close();
try {
clearRawResult();
// 开始请求工作
LogUtil.d("load: " + this.request.getRequestUri());
requestWorker = new RequestWorker();
requestWorker.request();
if (requestWorker.ex != null) {
throw requestWorker.ex;
}
rawResult = requestWorker.result;
} catch (Throwable ex) {
clearRawResult();
if (this.isCancelled()) {
throw new Callback.CancelledException("cancelled during request");
} else {
throw ex;
}
}
if (prepareCallback != null) {
if (this.isCancelled()) {
throw new Callback.CancelledException("cancelled before request");
}
try {
result = (ResultType) prepareCallback.prepare(rawResult);
} finally {
clearRawResult();
}
} else {
result = (ResultType) rawResult;
}
// 保存缓存
if (cacheCallback != null && HttpMethod.permitsCache(params.getMethod())) {
this.request.save2Cache();
}
if (this.isCancelled()) {
throw new Callback.CancelledException("cancelled after request");
}
} catch (HttpRedirectException redirectEx) {
retry = true;
LogUtil.w("Http Redirect:" + params.getUri());
} catch (Throwable ex) {
switch(this.request.getResponseCode()) {
// empty content
case 204:
// empty content
case 205:
case // disk cache is valid.
304:
return null;
default:
{
exception = ex;
if (this.isCancelled() && !(exception instanceof Callback.CancelledException)) {
exception = new Callback.CancelledException("canceled by user");
}
retry = retryHandler.canRetry(this.request, exception, ++retryCount);
}
}
}
}
if (exception != null && result == null && !trustCache) {
hasException = true;
throw exception;
}
return result;
}
Aggregations