//Glide.java
Glide(Engine engine, MemoryCache memoryCache, BitmapPool bitmapPool, Context context, DecodeFormat decodeFormat) {
...
}複製代碼
//GlideBuilder.java
Glide createGlide() {
...
return new Glide(engine, memoryCache, bitmapPool, context, decodeFormat);
}複製代碼
MemoryCache 內存緩存javascript
BitmapPool 圖片池html
DecodeFormat 圖片格式java
Engine 引擎類android
//MemorySizeCalculator.java
final int maxSize = getMaxSize(activityManager);
private static int getMaxSize(ActivityManager activityManager) {
//每一個進程可用的最大內存
final int memoryClassBytes = activityManager.getMemoryClass() * 1024 * 1024;
//判斷是否低配手機
final boolean isLowMemoryDevice = isLowMemoryDevice(activityManager);
return Math.round(memoryClassBytes
* (isLowMemoryDevice ? LOW_MEMORY_MAX_SIZE_MULTIPLIER : MAX_SIZE_MULTIPLIER));
}複製代碼
//MemorySizeCalculator.java
int screenSize = screenDimensions.getWidthPixels() * screenDimensions.getHeightPixels()
* BYTES_PER_ARGB_8888_PIXEL;(寬*高*4)
int targetPoolSize = screenSize * BITMAP_POOL_TARGET_SCREENS;(寬*高*4*4)
int targetMemoryCacheSize = screenSize * MEMORY_CACHE_TARGET_SCREENS;(寬*高*4*2)
//判斷是否超過最大值,不然就等比縮小
if (targetMemoryCacheSize + targetPoolSize <= maxSize) {
memoryCacheSize = targetMemoryCacheSize;
bitmapPoolSize = targetPoolSize;
} else {
int part = Math.round((float) maxSize / (BITMAP_POOL_TARGET_SCREENS + MEMORY_CACHE_TARGET_SCREENS));
memoryCacheSize = part * MEMORY_CACHE_TARGET_SCREENS;
bitmapPoolSize = part * BITMAP_POOL_TARGET_SCREENS;
}複製代碼
//GlideBuilder.java
memoryCache = new LruResourceCache(calculator.getMemoryCacheSize());複製代碼
int size = calculator.getBitmapPoolSize();
bitmapPool = new LruBitmapPool(size);複製代碼
DecodeFormat DEFAULT = PREFER_RGB_565複製代碼
//GlideBuilder.java
engine = new Engine(memoryCache, diskCacheFactory, diskCacheService, sourceService);複製代碼
//DiskCache.java
/** 250 MB of cache. */
int DEFAULT_DISK_CACHE_SIZE = 250 * 1024 * 1024;
String DEFAULT_DISK_CACHE_DIR = "image_manager_disk_cache";複製代碼
final int cores = Math.max(1, Runtime.getRuntime().availableProcessors());//得到可用的處理器個數
sourceService = new FifoPriorityThreadPoolExecutor(cores);複製代碼
diskCacheService = new FifoPriorityThreadPoolExecutor(1);複製代碼
//Glide.java
/** * @see #with(android.app.Activity) * @see #with(android.app.Fragment) * @see #with(android.support.v4.app.Fragment) * @see #with(android.support.v4.app.FragmentActivity) * * @param context Any context, will not be retained. * @return A RequestManager for the top level application that can be used to start a load. */
public static RequestManager with(Context context) {
RequestManagerRetriever retriever = RequestManagerRetriever.get();
return retriever.get(context);
}複製代碼
//RequestManagerRetriever.java
public RequestManager get(Context context) {
if (context == null) {
throw new IllegalArgumentException("You cannot start a load on a null Context");
} else if (Util.isOnMainThread() && !(context instanceof Application)) {
if (context instanceof FragmentActivity) {
return get((FragmentActivity) context);
} else if (context instanceof Activity) {
return get((Activity) context);
} else if (context instanceof ContextWrapper) {
return get(((ContextWrapper) context).getBaseContext());
}
}
return getApplicationManager(context);
}複製代碼
//RequestManagerRetriever.java
public RequestManager get(FragmentActivity activity) {
if (Util.isOnBackgroundThread()) {
return get(activity.getApplicationContext());
} else {
assertNotDestroyed(activity);
FragmentManager fm = activity.getSupportFragmentManager();
return supportFragmentGet(activity, fm);
}
}
RequestManager supportFragmentGet(Context context, FragmentManager fm) {
SupportRequestManagerFragment current = getSupportRequestManagerFragment(fm);
RequestManager requestManager = current.getRequestManager();
if (requestManager == null) {
requestManager = new RequestManager(context, current.getLifecycle(), current.getRequestManagerTreeNode());
current.setRequestManager(requestManager);
}
return requestManager;
}複製代碼
//RequestManagerRetriever.java
private RequestManager getApplicationManager(Context context) {
// Either an application context or we're on a background thread.
if (applicationManager == null) {
synchronized (this) {
if (applicationManager == null) {
// Normally pause/resume is taken care of by the fragment we add to the fragment or activity.
// However, in this case since the manager attached to the application will not receive lifecycle
// events, we must force the manager to start resumed using ApplicationLifecycle.
applicationManager = new RequestManager(context.getApplicationContext(),
new ApplicationLifecycle(), new EmptyRequestManagerTreeNode());
}
}
}
return applicationManager;
}複製代碼
//RequestManager.java
public DrawableTypeRequest<String> load(String string) {
return (DrawableTypeRequest<String>) fromString().load(string);
}複製代碼
//GenericRequestBuilder.java
public Target<TranscodeType> into(ImageView view) {
Util.assertMainThread();
if (view == null) {
throw new IllegalArgumentException("You must pass in a non null View");
}
if (!isTransformationSet && view.getScaleType() != null) {
switch (view.getScaleType()) {
case CENTER_CROP:
applyCenterCrop();
break;
case FIT_CENTER:
case FIT_START:
case FIT_END:
applyFitCenter();
break;
//$CASES-OMITTED$
default:
// Do nothing.
}
}
return into(glide.buildImageViewTarget(view, transcodeClass));
}複製代碼
1.Util.assertMainThread();這裏會檢查是否主線程,不是的話會拋出異常,因此into方法必須在主線程中調用.編程
2.當你沒有調用transform方法,而且你的ImageView設置了ScaleType,那麼他會根據你的設置,對圖片作處理(具體處理能夠查看DrawableRequestBuilder的applyCenterCrop或者applyFitCenter方法,咱們本身自定義BitmapTransformation也能夠參考這裏的處理).設計模式
3.view在這裏被封裝成一個Target.緩存
//GenericRequestBuilder.java
public <Y extends Target<TranscodeType>> Y into(Y target) {
Util.assertMainThread();
if (target == null) {
throw new IllegalArgumentException("You must pass in a non null Target");
}
if (!isModelSet) {
throw new IllegalArgumentException("You must first set a model (try #load())");
}
Request previous = target.getRequest();
if (previous != null) {
previous.clear();
requestTracker.removeRequest(previous);
previous.recycle();
}
Request request = buildRequest(target);
target.setRequest(request);
lifecycle.addListener(target);
requestTracker.runRequest(request);
return target;
}複製代碼
//GenericRequestBuilder.java
private Request buildRequest(Target<TranscodeType> target) {
if (priority == null) {
priority = Priority.NORMAL;
}
return buildRequestRecursive(target, null);
}複製代碼
//GenericRequestBuilder.java
private Request buildRequestRecursive(Target<TranscodeType> target, ThumbnailRequestCoordinator parentCoordinator) {
if (thumbnailRequestBuilder != null) {
...
Request fullRequest = obtainRequest(target, sizeMultiplier, priority, coordinator);
...
Request thumbRequest = thumbnailRequestBuilder.buildRequestRecursive(target, coordinator);
...
coordinator.setRequests(fullRequest, thumbRequest);
return coordinator;
} else if (thumbSizeMultiplier != null) {
ThumbnailRequestCoordinator coordinator = new ThumbnailRequestCoordinator(parentCoordinator);
Request fullRequest = obtainRequest(target, sizeMultiplier, priority, coordinator);
Request thumbnailRequest = obtainRequest(target, thumbSizeMultiplier, getThumbnailPriority(), coordinator);
coordinator.setRequests(fullRequest, thumbnailRequest);
return coordinator;
} else {
// Base case: no thumbnail.
return obtainRequest(target, sizeMultiplier, priority, parentCoordinator);
}
}複製代碼
//GenericRequestBuilder.java
private Request obtainRequest(Target<TranscodeType> target, float sizeMultiplier, Priority priority,
RequestCoordinator requestCoordinator) {
return GenericRequest.obtain(...);
}複製代碼
//GenericRequest.java
public static <A, T, Z, R> GenericRequest<A, T, Z, R> obtain(...) {
GenericRequest<A, T, Z, R> request = (GenericRequest<A, T, Z, R>) REQUEST_POOL.poll();
if (request == null) {
request = new GenericRequest<A, T, Z, R>();
}
request.init(...);
return request;
}複製代碼
//GenericRequestBuilder.java
public <Y extends Target<TranscodeType>> Y into(Y target) {
Request request = buildRequest(target);
...
requestTracker.runRequest(request);
...
}複製代碼
//GenericRequest.java
public void begin() {
...
if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
onSizeReady(overrideWidth, overrideHeight);
} else {
target.getSize(this);
}
...
}複製代碼
//GenericRequest.java
public void onSizeReady(int width, int height) {
...
loadStatus = engine.load(signature, width, height, dataFetcher, loadProvider, transformation, transcoder,
priority, isMemoryCacheable, diskCacheStrategy, this);
...
}複製代碼
//Engine.java
public <T, Z, R> LoadStatus load(...) {
...
EngineResource<?> cached = loadFromCache(key, isMemoryCacheable);
if (cached != null) {
cb.onResourceReady(cached);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Loaded resource from cache", startTime, key);
}
return null;
}
EngineResource<?> active = loadFromActiveResources(key, isMemoryCacheable);
if (active != null) {
cb.onResourceReady(active);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Loaded resource from active resources", startTime, key);
}
return null;
}
...
}複製代碼
//Engine.java
public <T, Z, R> LoadStatus load(...) {
...
EngineJob engineJob = engineJobFactory.build(key, isMemoryCacheable);
...
}複製代碼
//Engine.java
static class EngineJobFactory {
private final ExecutorService diskCacheService;
private final ExecutorService sourceService;
private final EngineJobListener listener;
public EngineJobFactory(ExecutorService diskCacheService, ExecutorService sourceService,
EngineJobListener listener) {
this.diskCacheService = diskCacheService;
this.sourceService = sourceService;
this.listener = listener;
}
public EngineJob build(Key key, boolean isMemoryCacheable) {
return new EngineJob(key, diskCacheService, sourceService, isMemoryCacheable, listener);
}
}複製代碼
//Engine.java
public <T, Z, R> LoadStatus load(...) {
...
EngineRunnable runnable = new EngineRunnable(engineJob, decodeJob, priority);
jobs.put(key, engineJob);
engineJob.addCallback(cb);
engineJob.start(runnable);
...
}複製代碼
//EngineJob.java
public void start(EngineRunnable engineRunnable) {
this.engineRunnable = engineRunnable;
future = diskCacheService.submit(engineRunnable);
}複製代碼
//EngineRunnable.java
public void run() {
...
try {
resource = decode();
} catch (Exception e) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Exception decoding", e);
}
exception = e;
}
...
if (resource == null) {
onLoadFailed(exception);
} else {
onLoadComplete(resource);
}
}複製代碼
//EngineRunnable.java
private Resource<?> decode() throws Exception {
if (isDecodingFromCache()) {
//第一次會走這
return decodeFromCache();//從磁盤緩存中讀取
} else {
return decodeFromSource();//從源資源中讀取
}
}複製代碼
//EngineRunnable.java
private Resource<?> decodeFromCache() throws Exception {
Resource<?> result = null;
try {
result = decodeJob.decodeResultFromCache();
} catch (Exception e) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Exception decoding result from cache: " + e);
}
}
if (result == null) {
result = decodeJob.decodeSourceFromCache();
}
return result;
}複製代碼
public void run() {
...
try {
resource = decode();
} catch (Exception e) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Exception decoding", e);
}
exception = e;
}
...
if (resource == null) {
onLoadFailed(exception);
} else {
onLoadComplete(resource);
}
}複製代碼
//EngineRunnable.java
private void onLoadFailed(Exception e) {
if (isDecodingFromCache()) {
stage = Stage.SOURCE;
manager.submitForSource(this);
} else {
manager.onException(e);
}
}複製代碼
//EngineJob.java
@Override
public void submitForSource(EngineRunnable runnable) {
future = sourceService.submit(runnable);
}複製代碼
//EngineRunnable.java
private Resource<?> decode() throws Exception {
if (isDecodingFromCache()) {
//第一次會走這
return decodeFromCache();//從磁盤緩存中讀取
} else {
//第二次會走這
return decodeFromSource();//從源資源讀取
}
}
//DecodeJob.java
public Resource<Z> decodeFromSource() throws Exception {
Resource<T> decoded = decodeSource();//獲取數據,並解碼
return transformEncodeAndTranscode(decoded);//處理圖片
}複製代碼
//DecodeJob.java
private Resource<T> decodeSource() throws Exception {
...
//拉取數據
final A data = fetcher.loadData(priority);
...
//解碼,並保存源資源到磁盤
decoded = decodeFromSourceData(data);
...
return decoded;
}複製代碼
//DecodeJob.java
private Resource<T> decodeFromSourceData(A data) throws IOException {
final Resource<T> decoded;
if (diskCacheStrategy.cacheSource()) {
//解碼並保存源資源(圖片)到磁盤緩存中
decoded = cacheAndDecodeSourceData(data);
} else {
long startTime = LogTime.getLogTime();
decoded = loadProvider.getSourceDecoder().decode(data, width, height);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logWithTimeAndKey("Decoded from source", startTime);
}
}
return decoded;
}複製代碼
//HttpUrlFetcher.java
@Override
public InputStream loadData(Priority priority) throws Exception {
return loadDataWithRedirects(glideUrl.toURL(), 0 /*redirects*/, null /*lastUrl*/, glideUrl.getHeaders());
}
private InputStream loadDataWithRedirects(URL url, int redirects, URL lastUrl, Map<String, String> headers)
throws IOException {
if (redirects >= MAXIMUM_REDIRECTS) {
throw new IOException("Too many (> " + MAXIMUM_REDIRECTS + ") redirects!");
} else {
// Comparing the URLs using .equals performs additional network I/O and is generally broken.
// See http://michaelscharf.blogspot.com/2006/11/javaneturlequals-and-hashcode-make.html.
try {
if (lastUrl != null && url.toURI().equals(lastUrl.toURI())) {
throw new IOException("In re-direct loop");
}
} catch (URISyntaxException e) {
// Do nothing, this is best effort.
}
}
urlConnection = connectionFactory.build(url);
for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
urlConnection.addRequestProperty(headerEntry.getKey(), headerEntry.getValue());
}
urlConnection.setConnectTimeout(2500);
urlConnection.setReadTimeout(2500);
urlConnection.setUseCaches(false);
urlConnection.setDoInput(true);
// Connect explicitly to avoid errors in decoders if connection fails.
urlConnection.connect();
if (isCancelled) {
return null;
}
final int statusCode = urlConnection.getResponseCode();
if (statusCode / 100 == 2) {
//請求成功
return getStreamForSuccessfulRequest(urlConnection);
} else if (statusCode / 100 == 3) {
String redirectUrlString = urlConnection.getHeaderField("Location");
if (TextUtils.isEmpty(redirectUrlString)) {
throw new IOException("Received empty or null redirect url");
}
URL redirectUrl = new URL(url, redirectUrlString);
return loadDataWithRedirects(redirectUrl, redirects + 1, url, headers);
} else {
if (statusCode == -1) {
throw new IOException("Unable to retrieve response code from HttpUrlConnection.");
}
throw new IOException("Request failed " + statusCode + ": " + urlConnection.getResponseMessage());
}
}複製代碼
//DecodeJob.java
private Resource<Z> transformEncodeAndTranscode(Resource<T> decoded) {
...
//對圖片作剪裁等處理
Resource<T> transformed = transform(decoded);
...
//將處理後的圖片寫入磁盤緩存(會根據配置來決定是否寫入)
writeTransformedToCache(transformed);
...
//轉碼,轉爲須要的類型
Resource<Z> result = transcode(transformed);
...
return result;
}複製代碼