From the source analysis of Android Glide library image loading process and characteristics _android

Source: Internet
Author: User

0. Basic knowledge
Glide A part of the word, I do not know what Chinese can be exact expression of meaning, in English words may be more appropriate in the wording, there are some words in the glide has a special meaning, I understand may not be in-depth, here first record.

(1) View: In general, refer to view in Android and its subclass controls (including customizations), especially ImageView. These controls can be drawn on top drawable
(2) The important concept of target:glide, the goal. It can refer to the target (Viewtarget) that encapsulates a view, or it may not contain view (Simpletarget).
(3) Drawable: Refers to the Android Drawable class or its subclasses such as bitmapdrawable. or a custom drawable (such as gifdrawable, etc.) implemented by the underlying drawable in glide
(4) Request-load requests, either a network request or any other request to download a picture, and a class in glide.
(5) Model: Data source provider, such as URL, file path, etc., can be obtained from model InputStream.
(6) Signature: Signature that uniquely identifies an object.
(7) Recycle (): Glide The Resource class has this method, indicating that the resource is not referenced and can be put into the pool (no space is freed at this time). Bitmap also has this approach in Android, which means that the memory used to release bitmap.

1. Main Features
(1) Support memory and disk image caching.
(2) supports GIF and WEBP format pictures.
(3) Automatically manage requests according to the Activity/fragment lifecycle.
(4) The use of bitmap pool can be used to bitmap reuse.
(5) for the recovery of bitmap will be active call recycle, reduce the system recovery pressure.

2. Overall design

Basic concepts
Requestmanager: Request management, each activity creates a requestmanager that manages the picture requests on the activity based on the lifecycle of the activity.
Engine: The engine that loads the picture, creates enginejob and decodejob according to request.
Enginejob: Picture loading.
Decodejob: Image processing.
Flow chart
Here is the general flowchart, detailed in the details below the process continues to analyze.

3. Introduction to Core classes

3.1 Gilde
used to save the configuration in the entire frame.
Important Method:

public static Requestmanager with (fragmentactivity activity) {
 Requestmanagerretriever retriever = Requestmanagerretriever.get ();
 return Retriever.get (activity);
}

For creating Requestmanager, here's what glide through the Activity/fragment Lifecycle Management request principle, which is the key, critical, critical, important thing I only say three times.
The main principle is to create a custom fragment, and then to manage the request by customizing the fragment lifecycle Operation Requestmanager.

3.2 Requestmanagerretriever

Requestmanager supportfragmentget (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;
}

This is to determine whether the current requestmanagerfragment exists requestmanager to ensure that an activity corresponds to a requestmanager, which facilitates the management of all request on an activity. When the requestmanager is created, the callback interface in Requestmanagerfragment is assigned to Requestmanager. Reach the life cycle of requestmanager listening requestmanagerfragment.

3.3 Requestmanager
member Variable:
(1) Lifecycle lifecycle for monitoring the requestmanagerfragment lifecycle.
(2) Requesttracker Requesttracker, which is used to hold all requests and processing requests that are currently requestmanager.
Important Method:

@Override
//Start paused request public
void OnStart () {
 resumerequests ();
}
Stop all requests
@Override public
void OnStop () {
 pauserequests ();
}
 
Close the request
@Override public
void OnDestroy () {
 requesttracker.clearrequests ();
}
 
Create Requestbuild public
drawabletyperequest<string> Load (string string) {return
 ( drawabletyperequest<string>) fromstring (). Load (String);
 
Public <y extends target<transcodetype>> y to (y Target) {
 ...
 Request previous = Target.getrequest ();
 Stops the request in the current target.
 if (previous!= null) {
 previous.clear ();//This place is critical, see Request resolution
 Requesttracker.removerequest ( previous);
 Previous.recycle ();
 }
 ...
 return target;
}

3.4 Drawablerequestbuilder
used to create the request. This includes a number of methods, mainly configured to load the image URL, size, animation, ImageView object, custom image processing interface.

3.5 Request
The main is the operation request, the method is very simple.

@Override public
void Clear () {
 ...
 if (resource!= null) {
 //the Resource
 Releaseresource (Resource) is released here;
 }
 ...
}

The rationale here is that when Target uses resource (resource see below), the reference value in resource is added to the value of the reference in the release resource resource minus one. When no target is used, the resource is released and put into the LRUCache.

3.6 Engineresource
implements the resource interface, uses the adornment pattern, inside contains the actual resource object

void release () {
 if (--acquired = 0) {
 listener.onresourcereleased (key, this);
 }
} 
 
void Acquire () {
 ++acquired;
} 
 
@Override public
void Recycle () {
 isrecycled = true;
 Resource.recycle ();
}

Acquire and release two methods are counting resource references, recycle releasing resources, which are usually triggered when the lrucache is saturated.

3.7 Engine (important)
the request engine, which primarily makes the initialization of the request.
3.7.1 Load method
This method is very long and will be divided into several steps analysis
(1) Get MemoryCache cache key that first creates the current request, obtains the cache from the MemoryCache by the key value, and determines whether the cache exists.

Private engineresource<?> Loadfromcache (Key key, Boolean ismemorycacheable) {
 ....
 . engineresource<?> cached = Getengineresourcefromcache (key);
 if (cached!= null) {
 cached.acquire ();
 Activeresources.put (Key, New Resourceweakreference (key, Cached, Getreferencequeue ()));
 return cached;
}
 
@SuppressWarnings ("unchecked")
private engineresource<?> Getengineresourcefromcache (key key) {
 resource<?> cached = Cache.remove (key);
 
 Final Engineresource result;
 ...
 return result;
}

(emphasis) the Cache.remove (key) used when fetching from the cache, then saves the value in Activeresources and then adds a reference count of resource.
Advantages:
> is using the resource will be in the activeresources, will not appear in the cache, when the MemoryCache buffer saturation or system memory is low, cleaning bitmap can directly call recycle, Do not worry about bitmap being used to cause exceptions, speeding up system recycling.
(2) Get cache in Activeresources
Activeresources saves the recouse through a weak reference and also gets the cache through the key.

Private engineresource<?> loadfromactiveresources (Key key, Boolean ismemorycacheable)

(3) Determine if the current request task already exists

Enginejob current = Jobs.get (key);
if (current!= null) {
 current.addcallback (CB);
 Return to New Loadstatus (CB, current);
}

If a task request already exists, the callback event is passed directly to the existing enginejob, which triggers the callback after the request succeeds.
(4) Perform request task

Enginejob enginejob = Enginejobfactory.build (key, ismemorycacheable);
Decodejob<t, Z, r> decodejob = new Decodejob<t, Z, r> (key, width, height, fetcher, Loadprovider, Transformatio N,
 transcoder, Diskcacheprovider, diskcachestrategy, priority);
Enginerunnable runnable = new Enginerunnable (Enginejob, decodejob, priority);
Jobs.put (key, enginejob);
Enginejob.addcallback (CB);
Enginejob.start (runnable);

3.8 enginerunnable
Request Execution runnable, the main function requests resources, processing resources, caching resources.

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;
} 
 
Private Resource<?> Decodefromsource () throws Exception {return
 decodejob.decodefromsource ();
}

Load DiskCache and network resources. The load DiskCache includes two because the glide default is to save the processed resources (after compression and cropping), and the caching method can customize the configuration. If the client specification is designed, the ImageView size is mostly the same to save picture load time and disk resources.

3.9 Decodejob
public resource<z> Decoderesultfromcache () throws Exception
Gets the processed resource from the cache. The key is the content of the above key is an object, you can get key and Orginkey. Decoderesultfromcache is a key to get the cache, Decodesourcefromcache () is through the Orginkey to get the cache.
Private resource<z> Transformencodeandtranscode (resource<t> decoded)
Processing and wrapping resources; caching resources.
Save the original resource
Private resource<t> Cacheanddecodesourcedata (A data) throws IOException
Save the processed resources
private void Writetransformedtocache (resource<t> transformed)

3.10 Transformation
resource<t> Transform (resource<t> Resource, int outwidth, int outheight);
Processing resources, which appear in the Bitmappool class, to achieve bitmap reuse.
3.11 Resourcedecoder
used to translate files, io into resource
3.12 Bitmappool
used to store the bitmap removed from the LRUCache for reuse when creating bitmap later.

4. Chat
Glide's architecture is highly extensible, but difficult to understand, various interfaces, generics, need a certain degree of learning to skilled use. The advantages of the
Glide:
(1) Support disk caching for processed resources. The
(2) is reused for bitmap through Bitmappool.
(3) uses the Activityresources cache for the resource that is being used to invoke recycle to accelerate memory recycling for bitmappool-saturated bitmap.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.