DYNAMICLOADAPK source code Parsing of Android open source project

Source: Internet
Author: User

1. Function Introduction 1.1 Introduction

DYNAMICLOADAPK is an open source Android plugin framework.

The advantages of the plug-in include: (1) module decoupling, (2) dynamic upgrade, (3) Efficient parallel development (faster compilation Speed) (4) load on demand, lower memory consumption and so on.

DYNAMICLOADAPK provides 3 development methods that allow developers to quickly integrate plug-in functionality without having to understand how it works.

    1. The host program is completely independent from the plugin
    2. Host Program open part interface for plug-in communication with it
    3. Part of the business logic of the host program coupling plug-in

Three development models can be seen in the demo.

1.2 Core Concepts

(1) Host: The main App, can load plug-ins, also known as host.
(2) Plugin: Plugin app, the app that is loaded by the host, also known as Plugin, can be the same Apk file as the normal App.

(3) Components: Refers to Android,,, Activity Service , the BroadcastReceiver ContentProvider current DL support Activity , Service and dynamic BroadcastReceiver .

(4) Plug-in components: components in the plug-in.

(5) Agent component: A component that is first launched when the plug-in component is started in the host's Manifest. Currently includes dlproxyactivity (Agent Activity), dlproxyfragmentactivity (proxy fragmentactivity), Dlproxyservice (proxy Service).

(6) Base component: The base class for plug-in components, currently includes dlbasepluginactivity (base class for Plug-in Activity), dlbasepluginfragmentactivity (base class for Plug-in fragmentactivity), Dlbasepluginservice (base class for Plug-in Service).

The core idea of dynamicloadapk principle can be summed up as two words: Agent. By registering the agent component in Manifest, a proxy component is started first when the plug-in component is started, and then the plug-in component is built and started through this proxy component.

2. Overall design


Above is the overall design of dynamicloadapk, dynamicloadapk is divided into four main modules:
(1) Dlpluginmanager
Plug-in management module, which is responsible for loading, managing and starting plug-in components.
(2) Proxy
The Proxy component module currently includes dlproxyactivity (Agent Activity), dlproxyfragmentactivity (proxy fragmentactivity), Dlproxyservice (proxy Service).
(3) Proxy Impl
The proxy component common logic module, unlike the Proxy in (2), is not a component, but the manager responsible for building and loading the plug-in component. These proxies Impl the plug-in component by reflection, then associates the plug-in with the Proxy component, and finally calls the plug-in component's OnCreate function to start.
(4) Base Plugin
The base class module of the plug-in component, currently includes dlbasepluginactivity (base class for Plug-in Activity), dlbasepluginfragmentactivity (base class for Plug-in fragmentactivity), Dlbasepluginservice (base class for Plug-in Service).

3. Flowchart


Above is the flowchart that invokes the plugin Activity, and the other component invocation process is similar.
(1) The plug-in is first loaded via the Dlpluginmanager loadapk function, which requires only one call per plugin.
(2) Start Agent Activity through Dlpluginmanager's startpluginactivity function.
(3) Agent activity starts the process of building and starting plugin activity.

4. Detailed design of Class 4.1 diagrams


The above is the main class of dynamicloadapk diagram, and the overall design of the same as described in three parts.
(1) for the Proxy section, each component has a dlattachable interface to facilitate the unification of different classes of the component, such as Activity, fragmentactivity. The public implementation portion of each component is uniformly placed in the corresponding Dlproxyimpl.
(2) for the Base Plugin part, each component has a Dlplugin interface, it is also convenient to unify the components of different classes.

Class 4.2 Features Introduction 4.2.1 Dlpluginmanager.java

The core classes of the DYNAMICLOADAPK framework include the following key features:
(1) Plug-in loading and management;
(2) The component that launches the plugin, currently includes Activity, Service.

Main properties:
mNativeLibDirThe directory path after the copy of the plugin Native Library to the host.
mPackagesHolderHashmap,key is the package name, value represents the plug-in information DLPluginPackage , and stores the plug-in information that has already been loaded.

Main functions:
(1) getinstance (context context)
Gets a singleton for the Dlpluginmanager object.
mNativeLibDirassign a variable to a full path named subdirectory under the data directory of the host app in the private constructor pluginlib .

(2) loadapk (String Dexpath)
Load the plug-in. The parameter dexpath is the file path of the plug-in.
This function calls loadapk (Final String Dexpath, Boolean hassolib) directly.

(3) loadapk (Final String Dexpath, Boolean hassolib)
Load Plugin Apk. The parameter dexpath is the file path of the plug-in, and Hassolib indicates whether the plugin contains so libraries.

Note: Before starting the component of the plug-in, you must first call one of the above two functions to load the plug-in and can only be called in the host.

The flowchart is as follows:

The LOADAPK function calls the PREPAREPLUGINENV function to load the plug-in, and the dashed box in the diagram is the Preparepluginenv flowchart.

(4) preparepluginenv (PackageInfo packageinfo, String Dexpath)
Load the plug-in and its resources. Flowchart such as.
Called createDexClassLoader(…) , createAssetManager(…) and the createResources(…) function completes the corresponding initialization section.

(5) Createdexclassloader (String Dexpath)
With DexClassLoader the load plug-in, the Dexclassloader initialization function is as follows:

dexPaththe path to the plug-in.
optimizedDirectoryThe optimized dex storage path. This sets the path to a subdirectory named under the current app data directory dex .
libraryPathThe path stored for the Native Library. This sets the path to the mNativeLibDir property, which is getInstance(Context) already initialized in the function.
parentThe parent Classloader,classloader uses the parental delegate mode to find the class, and the concrete loading method is visible ClassLoader Foundation.

    dependencies {         provided fileTree(dir: ‘dl-lib‘, include: [‘*.jar‘])     
The problem of 5.3 dynamicloadapk to be perfected

(1) The broadcasting has not yet been supported;
(2) If that in Base Plugin is not removed, it is necessary to overwrite the relevant method of Activity;
(3) The problem of possible duplication of plugin and host resource ID is not resolved, and the generation rule of resource ID in AAPT needs to be modified;
(4) does not support custom theme, does not support system transparent theme;
(5) The so processing in the plugin is abnormal;
(6) does not support static Receiver;
(7) does not support Provider;
(8) The plugin cannot be used directly;

5.4 Other plug-in solutions

In addition to the way dynamicloadapk is implemented by proxy, there are two types of plug-in scenarios:
(1) The method of Fragment and schema is implemented.
(2) Using bytecode library to dynamically generate a plug-in class A inherits from the plug-in Activity to start plug-in a. The plugin A has a fixed name and is already registered in Manifest.
Specifically visible: Android plugin

Finally H5 framework more and more, can also solve the plug-in solution of the automatic upgrade this part of the function, hardware, network is also improving, the future?

(6) Createassetmanager (String Dexpath)
Create Assetmanager to load plug-in resources.
In Android, the resource is accessed through the ID in the R.java. However, after the implementation of the plug-in, the host is unable to access the plug-in through the R file resources, so the use of reflection to generate the plug-in AssetManager , and the use of addAssetPath functions to load plug-in resources.

    private AssetManager createAssetManager(String dexPath) {         try {             AssetManager assetManager = AssetManager.class.newInstance();             Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);             addAssetPath.invoke(assetManager, dexPath);             return assetManager;         } catch (Exception e) {             e.printStackTrace();             return null;         }      

The parameterless constructors and functions of Assetmanager are addAssetPath hide called by reflection.

(7) createresources (Assetmanager Assetmanager)
The AssetManager Resources resource is read from this in the agent component, using the already loaded resource in the creation Resources .
For AssetManager Resources Further information, refer to: The search process Analysis for Android application resources.

(8) Copysolib (String Dexpath)
Call SoLibManager copy so libraries to the Native Library directory.

(9) Startpluginactivity (context context, dlintent dlintent)
When the plugin Activity is started, the function is called directly startPluginActivityForResult(…) .
The plugin's own internal Activity startup is still the calling Context#startActivity(…) method.

(Startpluginactivityforresult) (context context, dlintent dlintent, int requestcode)
To start the plugin Activity, the flowchart is as follows:

(one) Startpluginservice (final context context, final dlintent dlintent)
Start the plug-in Service.
The main logic in the function fetchProxyServiceClass(…) , the process and startPluginActivity(…) similar, just replaced by a callback method, after a variety of conditions are set up to invoke the native way to start the agent Service, no longer repeat.

(Bindpluginservice) (...) unbindpluginservice (...)
Bind or UnBind plugin Service. Logic and startPluginService(…) similar, no longer repeat.

4.2.2 Dlpluginpackage

The entity class that corresponds to the plugin information, the main attributes are as follows:

    public String packageName;      public String defaultActivity;      public DexClassLoader classLoader;      public AssetManager assetManager;      public Resources resources;      

packageNameThe package name for the plugin;
defaultActivityLauncher Main Activity for the plugin;
classLoaderClassLoader for loading plug-ins;
assetManagerAssetmanager for loading plug-in resources;
resourcesThe assetManager Resources resource is read from this in the proxy component, created with the resources already loaded in Resources .
packageInfoPackageManagerthe information of the plugin after being parsed.
This information will be DLPluginManager#loadApk(…) initialized at the time of the.

4.2.3 Dlattachable.java/dlserviceattachable.java

Dlserviceattachable and dlattachable are similar, the following first analysis Dlattachable.java.

Dlattachable is an interface, the main role is to unify all the different types of agent Activity, such as, DLProxyActivity DLProxyFragmentActivity convenient as the same interface unified processing.
DLProxyActivityAnd DLProxyFragmentActivity both implementations of this class.

Dlattachable currently has only one

An abstract function that binds a plug-in Activity and a proxy Activity , in which the pluginActivity parameters refer to the plug-in Activity .

Similarly dlserviceattachable, the role is to unify all the different types of proxy Service, implementing plug-ins Service and proxy Service bindings. Although at present only DLProxyService .

4.2.4 Dlplugin.java/dlserviceplugin.java

Dlplugin and Dlserviceplugin are similar, the following first analysis Dlplugin.java.

Dlplugin is an interface that contains Activity abstract functions such as life cycles, touches, menus, and so on.
Dlbase*activity implements this class, so that the plug-in's Activity indirectly implements this class.
The main role is to unify all the different types of plug-ins Activity, such as, Activity FragmentActivity convenient as the same interface unified processing, so this class called DLPluginActivity more appropriate.

The same Dlserviceplugin main role is to unify all the different types of plug-in Service, convenient as a unified interface unified processing, currently contains the Service life cycle and other abstract functions.

4.2.5 Dlproxyactivity.java/dlproxyfragmentactivity.java

Agent activity, which is the component registered in the host Manifest and the activity that is actually started when the plug-in activity is started, their internals will complete initialization and startup of the plug-in activity.

These two classes are the same, so this is only an analysis DLProxyActivity .

First look at its member variables.
(1). Dlplugin mremoteactivity
Represents a plug-in that really needs to be started Activity . This property name should be called pluginActivity more appropriate.
As we have described above, DLPlugin it is an interface that all plugins Activity have implemented indirectly.

Next in the agent Activity 's life cycle, touch, menu and other functions we will call the mremoteactivity related functions, simulation plug-in Activity related functions.

(2). Dlproxyimpl Impl
It mainly encapsulates the common logic of plug-ins Activity , such as initializing plug-ins activity and binding with agent activity, obtaining resources, etc.

4.2.6 Dlproxyimpl.java/dlserviceproxyimpl.java

Dlproxyimpl and Dlserviceproxyimpl are similar, the following first analysis Dlproxyimpl.java.

The Dlproxyimpl mainly encapsulates the common logic of plug-ins Activity , such as initializing plug-ins activity and binding with agent activity, acquiring resources, etc., which is equivalent to DLProxyActivity DLProxyFragmentActivity the public implementation part of the, and the core logic is presented below The OnCreate () function.

Main functions:
(1) Dlproxyimpl (activity activity)
constructor, the argument is the agent Activity.

(2) public void OnCreate (Intent Intent)
The OnCreate function is called in the agent Activity onCreate function, and the flowchart is as follows:

The first step 设置 intent 的 ClassLoader is for Unparcel parcelable data, which is described: Android.os.BadParcelableException.

(3) protected void launchtargetactivity ()
Loading the plug-in to start activity completes the initialization process, and the DLPlugin DLAttachable two-way binding of the attach function and the agent activity is achieved through the interface. The flowchart is shown in the Dashed box section.

(4) private void Initializeactivityinfo ()
Get the activityinfo of the plugin to be started.

(5) private void Handleactivityinfo ()
Sets information such as the subject of the agent Activity.

The other get* function is to obtain some information about the plugin, which is called by the agent Activity.

The same dlserviceproxyimpl mainly encapsulates the common logic of the plug-in Service , such as initializing the plug-in Service and binding to the agent Activity.

4.2.7 Dlbasepluginactivity.java/dlbasepluginfragmentactivity.java

Plug-in Activity base class, plug-ins Activity are to inherit one of Dlbasepluginactivity/dlbasepluginfragmentactivity (currently does not support actionbaractivity).

The main role is to determine whether some functions go directly to the parent logic or agent Activity or null logic, depending on the proxy.

DLBasePluginActivityInherit from Activity , and implement the interface at the same time DLPlugin . These two classes are the same, so this is only an analysis DLProxyActivity .
Main variables:

    protected Activity mProxyActivity;      protected Activity that;      protected DLPluginManager mPluginManager;      

mProxyActivityFor agent Activity, through attach(…) function binding.
thatWith the mProxyActivity equivalent, just to this distinguish with the pointer, to represent the real Context , here really refers to the agent is the agent activity, is not the case of the agent is equivalent to this.

4.2.8 Dlbasepluginservice.java

Plug-in service base class, the service in the plug-in to inherit the base class, the main role is to determine whether some functions go directly to the parent class logic or proxy Service or null logic.

The main variables are DLBasePluginActivity similar in meaning and are not repeated.
PS: Until now this class is still imperfect, at least and DLBasePluginActivity contrast, does not support the situation of non-agent

4.2.9 Dlintent.java

Inherits from Intent, encapsulating the PackageName and ClassName of the components to be started.

4.2.10 Solibmanager.java

Call SoLibManager copy so libraries to the Native Library directory.

Main functions:
(1) Copypluginsolib (context context, string Dexpath, String nativelibdir)
function to load the plug-in as a ZipFile form, loop through the files in it, and if it is the .so end file, conforms to the current platform CPU type, and has not yet copied the latest version, create a new Runnable copy so file.

4.2.11 Dlutils.java

Most of this class is useless or should not be placed in the function, perhaps the large version of the upgrade and maintenance of too many people after the maintenance of the tool function is not enough.

5.5.1 Plugins cannot be packaged Dl-lib.jar

The reason is that the plug-in and the host belong to different ClassLoader, and if you package Dl-lib.jar at the same time, the type conversion error is caused by ClassLoader isolation, which is visible: ClassLoader isolation

Eclipse Packaging solution See the Project homepage;
Android Studio Packaging solution See 5.2;
ANT packaging needs to modify the Compileclasspath property referenced by Dex Target in Build.xml.

5.2 Using dynamicloadapk under Android Studio

In the use of dynamicloadapk, there is a place to note that the plug-in APK can not pack the Dl-lib.jar file in the package, or will be error (Java.lang.IllegalAccessError:Class ref in Pre-verified class resolved to unexpected implementation). In other words, Dl-lib.jar to participate in the compilation, but not in packaging. The framework author has given the solution under Eclipse. I'll say here how to use it in Android Studio.

  All say the programmer's high wages, but very little understanding of their overtime pain, you are not every time in the mind, according to the time to reduce the wages are less, so will want to cry in the heart, or raise wages, or raise wages, or raise wages, why?? Because don't let us work overtime, this is impossible!!!

Want to subvert your work model? Want to reduce your overtime? Join us and explore the free mode of our programmers!

A native app for programmers to share knowledge and skills as a reward for online interactive interactive platform.

We have a top technical team of nearly 20 people, as well as excellent product and operations teams. Team leaders have more than 10 years of experience in the industry.

Now that we are recruiting the original heroes, you will be working with us to change the way programmers work and change the world of programmers! There will also be generous rewards. As our original participant, you will experience this programmer artifact with us, you can offer professional advice, we will adopt it humbly. Everyone will be a hero, and you will be the hero we need! You can also invite your friends to participate in this heroic recruiting interaction.

We will not delay you too much time, we only need your professional opinion, as long as you take 1 hours from one months, you can save two hours a day, everything is for our own!

To? Or not?

Connector Person code: 1955246408 (QQ)

DYNAMICLOADAPK source code Parsing of Android open source project

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.