Android Dynamic loading framework DL architecture and rationale analysis

Source: Internet
Author: User

Reprint Please indicate the source, this article from "Mr.simple's Blog".

I am participating in the blog star, click here to vote for me, thank you ~ Objective

In the last two years, the number of Android apps using plug-in technology is growing, in fact, the rapid expansion of business, the demand for more and more, the app is becoming bloated. Although the memory space of the mobile phone keeps increasing, but too big installs the package to the user also caused the psychological pressure. So everyone will think of the plug-in development approach, the app into a platform, rather than a separate app. The platform can be integrated with a variety of functions, functional modules are also added in the form of plug-ins, these plug-ins do not need to install, only need to download the user on demand to a location, and then use the dynamic loading in.

The idea is good, but to achieve a relatively stable dynamic loading framework is still a bit difficult, some big companies have a mature dynamic loading framework, but they do not open source. Fortunately, 2014 well-known CSDN Bo Director Liningyu Open source a model named DL Android Dynamic loading framework, the framework is simple, open source, compatibility is better, if you need to use plug-in development of friends can try the framework, but also interested in the open source project friends can contribute their own code, The address will be given at the end of the article.

For the basic situation and use of DL, I will not repeat, the author himself and the friends involved in the development has some good articles, for details, please refer to, APK dynamic loading framework (DL) parsing, DL dynamic loading framework technical documents, Android using dynamic loading framework DL for plug-in development. Here I will briefly introduce the basic structure and principle of DL, hoping to be able to provide some useful information for some friends.


Basic architecture

The most important and troublesome point for Android's dynamic loading framework may be basically two, the first is how the APK runs without installation, and the activity's basic declaration cycle can be called normally, and the second is that the activity can access the resource file in the form of R. Please refer to the following two articles, Android dynamic loading jar, APK implementation, Android source code Analysis-resource loading mechanism for loading the installation apk and Android resource loading mechanism. We give the solution to the DL in turn for these two issues.

loading not installed apk is relatively simple, is to load the APK file into the virtual machine via Dexclassloader, refer to the article given above. Here we mainly talk about the implementation of invoking the activity life cycle function. In the DL, there are two proxy classes, dlproxyactivity, dlproxyfragmentactivity, respectively, which inherit from activity and fragmentactivity, respectively. They represent the plug-in activity classes that are integrated from dlbasepluginactivity and dlbasepluginfragmentactivity, respectively, Dlbasepluginactivity and Dlbasepluginfragmentactivity, respectively, inherit from activity and fragmentactivity, I go! Isn't this a little messy? And listen to me slowly ~

In accordance with the DL development specification, your plugin's activity needs to inherit from Dlbasepluginactivity or dlbasepluginfragmentactivity, which encapsulates some basic invocation logic in two classes. Here we do not have too much attention, the focus is to see dlproxyactivity, dlproxyfragmentactivity. The mechanism of the DL is this, the real activity in the DL through intent activation can only be dlproxyactivity, dlproxyfragmentactivity, these two activity is registered in the host APK, So it can be started directly through the intent. And in two proxies is actually just a shell, they will call the plug-in activity corresponding life cycle function in their life cycle function. This is the introduction of a key class, Dlproxyimpl, which is responsible for parsing the plug-in APK's resources, ClassLoader, loading plug-ins through reflection Activity,dlproxyimpl loading the plugin activity and then invoking the proxy The activity's attach method passes the plug-in activity instance to the proxy activity, so that the proxy activity gets an instance of the plug-in activity. You can then invoke the function corresponding to the plugin activity in your own declaration cycle function.

Dlproxyimpl's launchtargetactivity function:

    @TargetApi (build.version_codes.            Ice_cream_sandwich) protected void launchtargetactivity () {try {//MClass is the class name of the target plug-in activity            class<?> Localclass = getClassLoader (). LoadClass (MClass);            constructor<?> localconstructor = Localclass.getconstructor (new class[] {});            Building plug-ins through reflection activity Object Instance = localconstructor.newinstance (new object[] {});            Mpluginactivity = (dlplugin) instance;            Inject the plug-in activity into the proxy activity ((dlattachable) mproxyactivity). Attach (Mpluginactivity, Mpluginmanager);            Plugin activity also obtains the reference to proxy Mpluginactivity.attach (mproxyactivity, mpluginpackage);            Bundle bundle = new bundle ();            Bundle.putint (Dlconstants.from, dlconstants.from_external);        Call the plugin activity's onCreate function, start the plugin activity mpluginactivity.oncreate (bundle);        } catch (Exception e) {e.printstacktrace (); }    }

The host will parse the APK when the plugin is loaded, such as its default startup activity, which will run the APK, then the activity jump in the plugin apk will need to pass the target activity's package name through the Dlintent class, The class name is passed to the DL framework, and the DL internals are parsed along with the corresponding loading logic.


dlproxyactivity Core code:

public class Dlproxyactivity extends activity implements dlattachable {//Plugin activity protected Dlplugin mremoteacti    vity;    Dlproxyimpl Loading plug-ins activity and resources such as private dlproxyimpl Impl = new Dlproxyimpl (this);        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Proxy onCreate Call Dlproxyimpl's onCreate, load plugin activity impl.oncreate (getintent ()); }//After loading the plug-in activity, the plugin activity is passed to the proxy activity @Override public void Attach (Dlplugin remoteactivity, Dlpluginman    Ager PlugInManager) {mremoteactivity = remoteactivity;  }//Get resources, Dlproxyimpl loaded plug-in APK resources, through the agent resources here operation, so that plug-in activity inside can access the resource file through R @Override Public Resources Getresources ()    {return impl.getresources () = = null? Super.getresources (): Impl.getresources (); }/*********************** The following are the life cycle functions of the agent plug-in activity ***********************/@Override protected void OnStart ()        {Mremoteactivity.onstart (); SupEr.onstart ();        } @Override protected void Onrestart () {Mremoteactivity.onrestart ();    Super.onrestart ();        } @Override protected void Onresume () {mremoteactivity.onresume ();    Super.onresume ();        } @Override protected void OnPause () {mremoteactivity.onpause ();    Super.onpause ();        } @Override protected void OnStop () {mremoteactivity.onstop ();    Super.onstop ();        } @Override protected void OnDestroy () {Mremoteactivity.ondestroy ();    Super.ondestroy (); }//code omitted}

Let's take a look at another point, the plugin APK's resource load. For the APK resource loading mechanism also refer to the above-mentioned article, we look directly at the code.

    Private Dexclassloader Createdexclassloader (String dexpath) {File Dexoutputdir = Mcontext.getdir ("Dex", Contex        T.mode_private);        Dexoutputpath = Dexoutputdir.getabsolutepath (); Create ClassLoader Dexclassloader loader = new Dexclassloader (Dexpath, Dexoutputpath, Mnativelibdir, M        Context.getclassloader ());    return loader; }//Build Assetmanager on the path of the plugin apk, add the path where its resources are located to Assetmanager, and build a resources object from Assetmanager, which is the resource object of the plugin apk. Plugin APK internal access to resources is through this resource object private Assetmanager Createassetmanager (String dexpath) {try {Assetmanager a            Ssetmanager = AssetManager.class.newInstance ();            Method Addassetpath = Assetmanager.getclass (). GetMethod ("Addassetpath", String.class);            Addassetpath.invoke (Assetmanager, Dexpath);        return assetmanager;            } catch (Exception e) {e.printstacktrace ();        return null; }} private Resources createresources (Assetmanager assetmanageR) {Resources superres = mcontext.getresources (); Resources Resources = new resources (Assetmanager, Superres.getdisplaymetrics (), Superres.getconfiguration ()        );    return resources; }

In this way, is equal to the plug-in activity's life cycle to the proxy activity agent, and plug-in activity of the start and resource access to the Dlproxyimpl agent. In this way, the plug-in activity is initiated through two agents, and resource access issues are resolved.

Finally, we look at the basic structure of the DL through a graph.

Dlpluginmanager load, manage the plug-in package, Dlintent is the information carrier of the jump between plugins. Base Plugin activity is the base class for plug-in activity, encapsulating agent operations. Proxy activity Agent plug-in activity's life cycle function, is also the shell of the plugin activity. Dlproxy is responsible for loading plug-ins activity and resource operations. In this way, the entire dynamic loading framework is running, more details of interested friends to see the source bar.


Late features

1. Support Service, static broadcast, ContentProvider

Bug

1. Plugin Transparent Theme Support

2. Rewrite of the full activity API


Finally give the DL framework GitHub address, I hope more people participate in the development of DL framework.


I am participating in the blog star, click here to vote for me, thank you ~


Android Dynamic loading framework DL architecture and rationale 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.