Android Assetmanager <1>

Source: Internet
Author: User



Assetmanager is an Android explorer that manages all the resources on the Android system. Resources can be divided into system level and application level.

System level is mainly framework-res.apk, that is, compiled Framework/base/core/res directory, of course, sometimes custom systems will have customized resources, generally placed in ~/vendor/overlay/... Below, you can include vendor/overlay/framework the following file resources in the Framework/base/core/res android.mk, so that you can generate a total framework-res.apk out, can also be divided into two, one is the system native framework-res.apk, one can be customized-res.apk, if it is separate, then you need to modify the framework of the program, the custom res added to the path, or the system or application still cannot find .

In addition, the following resources are framework/base/data/, usually fonts, system sounds, and videos with their own media. Custom systems often encounter tweaks to what system fonts, sounds, or videos that come with media, from the time of the Nokia era.

The application level is primarily a developer's various resources and assets directories in the Res directory in the app project.

The common feature of the above resources is the need for a configuration message: including national language, time zone, screen density (and screen size), etc., such a distinction can be used in different areas of different resources, different devices using different resources---obvious, screen adaptation. iphone The app doesn't need to be a special fit!


A resource is loaded from the creation (or start of the first activity that runs the app). Activitythread creates the activity object, and init in the activity's parent class, Contextimpl, starts initializing the resource loading operations.

The following starts with the CONTEXTIMPL init:

final void Init (loadedapk packageinfo, IBinder Activitytoken, Activitythread mainthread, Resources container, S        Tring Basepackagename, Userhandle user) {mpackageinfo = PackageInfo; Mbasepackagename = basepackagename! = null?        BasePackageName:packageInfo.mPackageName;        Mresources = Mpackageinfo.getresources (Mainthread); if (mresources! = null && container! = null && container.getcompatibilityinfo (). Application                Scale! = Mresources.getcompatibilityinfo (). Applicationscale) {if (DEBUG) { LOG.D (TAG, "loaded context has different scaling.            Using container ' s "+" Compatiblity Info: "+ container.getdisplaymetrics ()); } mresources = Mainthread.gettoplevelresources (Mpackageinfo.getresdir (), Display.default_di        Splay, NULL, Container.getcompatibilityinfo ()); } mmainthread = Mainthread;       Mactivitytoken = Activitytoken;        Mcontentresolver = new Applicationcontentresolver (this, mainthread, user);    Muser = user; }

Access to the object resource of the resource:

Mresources = Mainthread.gettoplevelresources (                    mpackageinfo.getresdir (), display.default_display,                    null, Container.getcompatibilityinfo ());

Jump to the Activitythread class:

Resources gettoplevelresources (String resdir,            int Displayid, Configuration overrideconfiguration,            Compatibilityinfo compinfo) {

In this method:

Weakreference<resources> WR = Mactiveresources.get (key);            r = WR! = null? Wr.get (): null;            if (r! = null) slog.i (TAG, "isuptodate" + Resdir + ":" + r.getassets (). IsUpToDate ());            if (r! = null && r.getassets (). IsUpToDate ()) {                if (false) {                    SLOG.W (TAG, "Returning cached resources" + R + "" + Resdir                            + ": appscale=" + r.getcompatibilityinfo (). Applicationscale);                }                return r;            }

Activitythread maintains the app and its corresponding resource resource through a HASHMAP structure mactiveresources. Through R.getassets (). IsUpToDate to determine if there is a corresponding resource and the resources are not outtime (but this outtime do not know why to check, temporarily unclear), the general app will have a corresponding, return true, then will return to get R.

But if the resdir is not found, then the program creates Assetmanager and loads the resources:

Assetmanager assets = new Assetmanager ();        if (Assets.addassetpath (resdir) = = 0) {            return null;        }

Method:

Addassetpath

Very important, in many places are used, but this method is marked @hide, so generally if you want to use is reflected in the way, such as: if you put a picture into the assets folder, then will not produce r.id, then you need developers through the above method load to the resource path down, Can be provided to other use, common such as resource plug-in, resources in another plugin, then all the resources in this plugin need to be added to the resource path before it can be used by the host. That's nonsense, so just remember.

Public native final int addassetpath (String path);    /**     * ADD Multiple sets of assets to the asset manager at once.  See     * {@link #addAssetPath (String)} For more information.  Returns array     of * cookies for each added asset with 0 indicating failure, or null if     * The input array of paths I s null.     * {@hide}     */public    final int[] addassetpaths (string[] paths) {        if (paths = = null) {            return null;        }        int[] cookies = new Int[paths.length];        for (int i = 0; i < paths.length; i++) {            Cookies[i] = Addassetpath (Paths[i]);        }        return cookies;    }

It is obvious that this method is a native method: In the end it is in AssetManager.cpp

BOOL Assetmanager::addassetpath (const string8& path, void** cookie) {    Automutex _l (mLock);    Asset_path ap;

In this function, the path is added to a vector table of vectors:

Skip If we have it already.    for (size_t i=0; i<massetpaths.size (); i++) {        if (Massetpaths[i].path = = Ap.path) {            if (cookie) {                *cookie = (void*) (i+1);            }            return true;        }    }    ALOGV ("In%p Asset%s path:%s", this,         ap.type = = kfiletypedirectory? "dir": "Zip", ap.path.string ());    Massetpaths.add (AP);


There is also a program, when loading the FRAMEWORK-RES.APK package, the system will continue to check whether there are replacement resources, that is, overwrite the resources---coverage mechanism:

Add overlay packages for/system/framework;        Apps is handled by the//(Java) Package Manager if (strncmp (path.string (), "/system/framework/", 18) = = 0) { When there is a environment variable for/vendor, this//should being changed to something similar to how Andro        Id_root//And Android_data is used in this file.        String8 Overlaypath ("/vendor/overlay/framework/");        Overlaypath.append (Path.getpathleaf ());            if (Temp_failure_retry (Access (overlaypath.string (), r_ok) = = 0) {Asset_path OAP;            Oap.path = Overlaypath;            Oap.type =:: Getfiletype (Overlaypath.string ()); BOOL Addoverlay = (Oap.type = = kfiletyperegular); only. APKS Supported as Overlay if (addoverlay) {Oap.idmap = Idmappathforpackagepath (Overlay                Path); if (isidmapstalelocked (Ap.path, Oap.path, Oap.idmap)) {Addoverlay = createidmapfilelocked (Ap.path, OAP      . path, Oap.idmap);          }} if (Addoverlay) {massetpaths.add (OAP);            } else {ALOGW ("Failed to add overlay package%s\n", overlaypath.string ()); }        }    }

This is said before, and will go to see if there is a replacement resource under the Vendor/overlay/framework. Here is the system's resource coverage mechanism. But I did a search, and the Internet has the following:

If the handset manufacturer wants to use the above resource-covering mechanism to customize its own system resources, it also needs to provide a Idmap file that explains which default resources the APK file in the/vendor/overlay/framework/directory will overwrite the system with. The resource ID is used to describe it, so the Idmap file is actually a resource ID mapping file. This idmap file is eventually saved in the/data/resource-cache/directory and is ordered in a certain format, for example, assuming that the mobile vendor provides an overlay resource file that is/vendor/overlay/framework/ framework-res.apk, the corresponding Idmap file will be saved in the directory protected in the form of the name @[email Protected]@[email/data/resource-cache/] @idmap. For an        Android system resource Overlay (Overlay) mechanism, refer to the read file in the Frameworks/base/libs/utils directory

As seen from this passage, web-based substitution is the creation of a new res.apk of vendor/overlay/framework/resources to provide a replacement solution. In fact, did not see too clearly, and read file is not found (temporarily refer to the online:/http blog.csdn.net/tuhuolong/article/details/45939879). And the so-called Idmap file looks very tall, at first I thought it needed to be artificially generated, a little dazed. I later printed the log out of this place:

Then restart the machine:

When loading the framework-res.apk, the above judgment is established. Further typing Overlaypath:

If you can change the program, then in fact, vendor.../can be changed to any directory, so that the system based on any directory lookup is good.

As for what to provide Idmap, I was confused, if Overlaypath effective, execute the following there is idmap, as to what needs to provide what, and what format and so on, a little scary, these are the following function and return Idmap

Oap.idmap = Idmappathforpackagepath (Overlaypath);

if (isidmapstalelocked (Ap.path, Oap.path, Oap.idmap)) {                    Addoverlay = createidmapfilelocked (Ap.path, Oap.path, OAP.IDMAP);                }

Then add the overlay resource to the resource path by following the down.

if (addoverlay) {                massetpaths.add (OAP);            


If it is an app, then the above program function in front of that comment gives a hint, if it is the app can go to Packagemanager in the Getresourcesforapplication method, but this method is an abstract approach, Actually want to see in the Applicationpackagemanager:

@Override public Resources getresourcesforapplication (        applicationinfo app) throws namenotfoundexception {        if (App.packageName.equals ("System")) {            return MContext.mMainThread.getSystemContext (). Getresources ();        }        Resources r = mContext.mMainThread.getTopLevelResources (                app.uid = = Process.myuid ()? App.sourcedir: App.publicsourcedir,                        display.default_display, NULL, mcontext.mpackageinfo);        if (r! = null) {            return r;        }        throw new Namenotfoundexception ("Unable to open" + App.publicsourcedir);    }

I print the log out of this place:



This is obvious, if it is a custom system can make a insinuate table, such as the above is the desktop launcher APK, if you want to change the theme of the whole desktop, then you can do a launcher_plugin.apk into the system, But the resources of the two projects should correspond, such as launcher has a r.id.pumpkin resources, then launcher_plugin.apk must also have, because this is the whole replacement. So if the above App.sourcedir equals the desktop, Replace the value of this app.sourcedir with launcher_plugin.apk, then launcher will use the plugin resource. This is the whole project replacement.

Digression: I remember my previous company if custom system resources are vendor/overlay/framework to add new resources, instead of replacing them, the equivalent is to do a set of resources (subject resources, etc.), and then let the team all the apps use the company's customized resources, Instead of replacing the way, so there is a problem, the customization of resources changed, the above all the app to correspond to change, but one of the benefits is to keep the original resources, so that the other app theme will not affect, but if it is replaced by the way, it will affect the third-party app, Because at that time the third party's use of the system Resources section will be customized by the OEM, that is, running on different mobile phones app visual effect is not the same.


The next article looks at how to get a single resource ID information.
























Android Assetmanager <1>

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.