Android's drawable caching mechanism source code analysis

Source: Internet
Author: User

The way Android gets drawable is generally resources.getdrawable (int), and the framework returns you to a top-level abstract drawable object. In the framework, the system uses a way to conserve memory. To prove this, let's write a little demo:

We have introduced a simple picture test.png in our Android project. Since we're just trying to get to the conclusion of the meta, we define a simple activity and replicate its OnCreate method:

list<bitmap> list = new arraylist<bitmap> ();    Bitmap Bitmap = null;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        for (int i = 0; i <; i + +) {            bitmap  = Bitmapfactory.decoderesource (Getresources (), r.drawable.test);            List.add (bitmap);        }        ImageView IV = new ImageView (this);        Iv.setimagebitmap (bitmap);        This.setcontentview (iv);    }
Maybe you're wondering why you need a list to store the bitmap, which is important to avoid a GC-induced memory release. All right, we'll print out our memory and we'll find that we've added 10 bitmap. The actual memory occupied is: 26364K. The way we are transforming into drawable:

list<drawable> list = new arraylist<drawable> ();    Drawable bitmap = null;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        for (int i = 0; i < ten; I + +) {            bitmap  = This.getresources (). getdrawable (r.drawable.test);            List.add (bitmap);        }        ImageView IV = new ImageView (this);        Iv.setimagedrawable (bitmap);        This.setcontentview (iv);    }

We re-print the memory and found that the memory has dropped to: 7844K, this part of the data basically proves our conclusion. So is it possible that the resources cache the same drawable. Of course not, you can write a simple code test:

drawable D1 = this.getresources (). getdrawable (r.drawable.test);        drawable D2 = This.getresources (). getdrawable (r.drawable.test);        System.out.println (">>>d1 = = D2?") = "+ (D1 = = D2));
You will find that the output is false. In fact, we basically reached a consensus on the framwork, the key to packaging drawable when the combination mode is introduced, the framework itself caches the core metadata of your drawable.

Resources.java drawable loaddrawable (typedvalue value, int id)            throws notfoundexception {... Drawable dr = Getcacheddrawable (iscolordrawable? Mcolordrawablecache:mdrawablecache, key);

From the code can be seen, the system of drawable mainly divided into two major categories, in fact, there is a class familiar with the preload class drawable, but not as we discuss the focus, because we load is not a color type of drawable, So our corresponding pool of privileges is implemented by the Mdrawablecache object.
resources.javaprivate drawable getcacheddrawable (longsparsearray<weakreferenc E<constantstate>> Drawablecache, Long key) {synchronized (maccesslock) {Weakrefere            Nce<drawable.constantstate> WR = Drawablecache.get (key);                if (WR! = NULL) {//We have the key drawable.constantstate entry = Wr.get (); if (entry! = null) {//LOG.I (TAG, "Returning Cached drawable @ #" +//Intege                    R.tohexstring ((Integer) key). Intvalue ())//+ "in" + This + ":" + entry);                Return entry.newdrawable (this);                } else {//Our entry have been purged drawablecache.delete (key);    }}} return null; }
By invoking the code, we find that we are stored in a data pool that is not our drawable object at all, but rather an object called the Drawable.constantstate type, wrapped up with a weak reference. Constantstate is an abstract class, with many subclasses implemented

public static abstract class Constantstate {/** * Create a new drawable without supplying resources the CA  Ller * is running in. Note that using this means the density-dependent * Drawables (like bitmaps) is not being able to update their targe T * density correctly.         One should use {@link #newDrawable (Resources)} * instead to provide a resource.        */Public abstract drawable newdrawable ();  /** * Create A new drawable instance from it constant state. This * must is implemented for Drawables, change based on the target * density of their caller         s depending on whether it's * in compatibility mode).        */Public drawable newdrawable (Resources res) {return newdrawable (); }/** * Return a bit mask of configuration changes that would impact * this drawable (and thus Requi         Re completely reloading it). */Public AbstraCT int getchangingconfigurations ();        /** * @hide * */Public Bitmap Getbitmap () {return null; }    }
Since we are using bitmapdrawable, the constantstate corresponding to Bitmapdrawable is Bitmapstate

Final static class Bitmapstate extends Constantstate {Bitmap mbitmap;        int mchangingconfigurations;        int mgravity = Gravity.fill;        Paint Mpaint = new paint (default_paint_flags);        Shader.tilemode mtilemodex = null;        Shader.tilemode Mtilemodey = null;        int mtargetdensity = Displaymetrics.density_default;        Boolean mrebuildshader;        Boolean mautomirrored;        Bitmapstate (Bitmap Bitmap) {mbitmap = Bitmap;            } bitmapstate (Bitmapstate bitmapstate) {this (BITMAPSTATE.MBITMAP);            Mchangingconfigurations = bitmapstate.mchangingconfigurations;            mgravity = bitmapstate.mgravity;            Mtilemodex = Bitmapstate.mtilemodex;            Mtilemodey = Bitmapstate.mtilemodey;            mtargetdensity = bitmapstate.mtargetdensity;            Mpaint = new Paint (bitmapstate.mpaint);            Mrebuildshader = Bitmapstate.mrebuildshader;   mautomirrored = bitmapstate.mautomirrored;     } @Override Public Bitmap Getbitmap () {return mbitmap;        } @Override Public drawable newdrawable () {Return to New bitmapdrawable (this, null);        } @Override Public drawable newdrawable (Resources res) {return new bitmapdrawable (this, res);        } @Override public int getchangingconfigurations () {return mchangingconfigurations; }    }
We can see the bitmapstate corresponding Newdrawable method, which passes itself as a parameter to the Bitmapdrawable object, which means bitmapdrawble combines the same bitmapstate. This enables the reuse of the same bitmap resource.

With this, I'm sure everyone knows the same about how bitmap is removed from the cache, and we'll look at how constantstate is deposited.

Resources.loaddrawable () {... InputStream is = Massets.opennonasset (Value.assetcookie, file, Assetmanager.access_streami        NG);                        System.out.println ("opened file" + file + ":" + is);                        MIUI MOD://dr = Drawable.createfromresourcestream (this, value, is, file, null);                        Dr = Createfromresourcestream (this, value, is, file, id);            Is.close ();.. if (dr! = null) {dr.setchangingconfigurations (value.changingconfigurations);            cs = Dr.getconstantstate (); if (cs = null) {if (mpreloading) {final int changingconfigs = Cs.getchangingconfigura                    tions ();                                if (iscolordrawable) {if (Verifypreloadconfig (changingconfigs, 0, Value.resourceid, "Drawable")) {SpreloadedcolordrawabLes.put (key, CS);                                }} else {if (Verifypreloadconfig (Changingconfigs, Layout_dir_config, Value.resourceid, "drawable")) {if (changingconfigs&layout_dir_conf                                IG) = = 0) {//If This resource does not vary based on layout direction,                                We can put it in all of the preload maps.                                Spreloadeddrawables[0].put (key, CS);                            Spreloadeddrawables[1].put (key, CS);                                } else {//Otherwise, only in the layout dir we loaded it for. Final longsparsearray<drawable.constantstate> preloads = Spreloadeddrawa                                Bles[mconfiguration.getlayoutdirection ()];                            Preloads.put (key, CS);    }                    }}} else {synchronized (maccesslock) { LOG.I (TAG, "Saving cached drawable @ #" +//integer.tohexstring (Key.intva                        Lue ())//+ "in" + This + ":" + cs); if (iscolordrawable) {mcolordrawablecache.put (key, New weakreference<drawable.constantstate                        > (CS));                        } else {Mdrawablecache.put (key, New Weakreference<drawable.constantstate> (CS)); }                    }                }            }...}
As you can see, when you are reborn into a drawable, you take Drawable's constantstate out of the drawable and put it in your cache pool.





Android's drawable caching mechanism source code analysis

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.