本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点
Glide通过生命周期取消加载
生命周期回调过程
onStop
—>RequestManager.onStop
–>RequestTracker.pauseRequest
–> SingleRequest.pause
–> SingleRequest.cancel
—> Engine.cancel
—> EngineJob.removeCallback
—> 如果所有的回调监听都移除了
–> DecodeJob.cancel
//EngineJob.class
synchronized void removeCallback(ResourceCallback cb) {
stateVerifier.throwIfRecycled();
cbs.remove(cb);
if (cbs.isEmpty()) {
cancel();
boolean isFinishedRunning = hasResource || hasLoadFailed;
if (isFinishedRunning && pendingCallbacks.get() == 0) {
release();
}
}
}
- 如果任务没有执行,就从队列里移除,取消任务
- 如果任务已经执行,就利用isCancelled标记在停止流程
//DecodeJob.class
public void cancel() {
isCancelled = true;
DataFetcherGenerator local = currentGenerator;
if (local != null) {
local.cancel();
}
}
上面最终会调用到具体的获取图片的任务,比如从网络获取图片的HttpUrlFetcher
//HttpUrlFetcher.class
private volatile boolean isCancelled;
@Override
public void cancel() {
// TODO: we should consider disconnecting the url connection here, but we can't do so
// directly because cancel is often called on the main thread.
isCancelled = true;
}
//内部是通过HttpURLConnection来从网络获取数据
private InputStream loadDataWithRedirects(
URL url, int redirects,