Bottleneck
Most friends start to get into this problem because the app is bursting and the number of methods exceeds the limit of one of Dex's maximum 65535 methods, so there's a plug-in concept that divides an app into multiple plugins (APK or related format)
The benefits of a plug-in dynamic loading architecture are great for us:
Compile speed boost
After the project was split into more than 10 sub-projects, the cumbersome shortcomings of the Android Studio compilation process were rapidly magnified.
Start Speed boost
Google provides the MULTIDEX scheme, the main thread will perform all the Dex decompression, dexopt, loading operations, this is a very long process, the user will obviously see a long black screen, more likely to cause the main thread of the ANR, resulting in the initial initialization failure.
A/B Testing
You can independently develop the AB version of the module instead of writing the AB version code in the same module.
Optional modules to download on demand
? For example, a module for debugging functions can be loaded when needed, reducing the Size of the app
Introduction noun
Plug-in –apk is divided into the host and plug-ins section, plug-ins when needed to load in
Hot fix – updated classes or plug-ins when the granularity is small, we call it hot fixes, which are commonly used to fix bugs
Hot Update –2016 Google's Android Studio launched the instant Run feature and presented 3 nouns
"Hot Deployment" – Simple modifications within the method without restarting the app and activity. The "Warm deployment" –app does not require a reboot, but the activity needs to be restarted, such as resource modifications. A "cold Deployment" –app requires a reboot, such as a change in the inheritance relationship or a change in the signature of a method.
Mulitidex start
When the Android system installs an application, one step is to optimize for Dex, a process that has a dedicated tool to handle, called dexopt. The execution of the dexopt is performed when the Dex file is loaded for the first time. This process generates a ODEX file, which is optimised Dex. Executing ODex is much more efficient than directly executing the Dex file.
But in the early days of Android, Dexopt had a problem, dexopt would retrieve the method ID of each class, and there would be a list structure inside. However, the length of the list is saved with a short type, resulting in no more than 65,536 method IDs. When a project is large enough, it is clear that the upper limit of this method is not enough. Although dexopt fixed this issue in the new version of Android, we still need to be compatible with the low-version Android system.
In order to solve the problem of the limit of the number of methods, the Dex file needs to be split into two or more, to this end, Google launched the Multidex compatibility package, with Androidstudio implementation of an APK contains multiple Dex features.
The problems caused by Mulitdex are:
The installation of the Dex file when the app is installed on the phone is complex (complex) and may cause ANR because the second Dex file is too large.
Apps that use Mulitdex may not start on 4.0 (API level 14) machines, because Dalvik linearalloc bugs (Issue 22586).
Apps using Mulitdex may be Dalvik linearalloc limit (Issue 78035) Crash during runtime. The memory allocation limit is increased in version 4.0, but apps on machines under 5.0 still have this limitation.
When the main Dex is Dalvik by the virtual machine, which classes must be in the main Dex file, this problem is more complicated. Build tools can handle this.
Implementation of plug-in needs to address the technical point of resources such as finer (how to solve the problem of resource conflict) code how to load access access? What is included in the admin background of the plugin? Question 1 How the resource loads scenario one:
The plug-in APK resource decompression, through the operation of the file way to use, this is only theoretically feasible, the actual use of time still have a lot of problems. (mainly confused after the confusion forced)
Scenario Two:
Override methods such as GetResource () Getasset () in the Context. Resource conflicts require an extended AAPT implementation.
Load of run-time resources
Normally we use resources, which are accessed through the Assetmanager class and the resource class. The methods to get them are located in the context class.
Context.java
/** Return an AssetManager instance for your application‘s package. */publicabstractgetAssets();/** Return a Resources instance for your application‘s package. */publicabstractgetResources();
They are two abstract methods, specifically implemented in the Contextimpl class. After the resources object is initialized in the Contextimpl class, the subsequent context subclasses, including the activity, service, and so on, can read the resource through both methods.
Contextimpl.java
privatefinal Resources mResources;@OverridepublicgetAssets() { return getResources().getAssets();}@OverridepublicgetResources() { return mResources;}
Now that we know which apk the resource ID should be read from (at compile time we've tagged the package that the resource belongs to in the first byte of the resource ID), we can instruct the application to read the resource in the correct place as long as we rewrite the two abstract methods.
As for reading resources, Assetmanager has a hidden method Addassetpath, which can add a resource path for Assetmanager.
/*** Add an additional set of assets to the asset manager. This can be* either a directory or ZIP file. Not for use by applications. Returns* the cookie of the added asset, or 0 on failure.* {@hide}*/publicfinalintaddAssetPath(String path) { synchronized (this) { int res = addAssetPathNative(path); makeStringBlocks(mStringBlocks); return res; }}
We just call this method by reflection, and then we tell the plugin apk location to the Assetmanager class, and it will complete the task of loading the resources according to the RESOURCES.ARSC and compiled resources within the APK.
Above we can already load plug-in resources, but use a lot of custom class implementation. The "seamless" experience requires a single step: using instrumentation to take over the creation of all the components of activity, service, and, of course, the resources they use.
In other words, the activity, service and other system components are executed through the Android.app.ActivityThread class in the main thread. The Activitythread class has a member called Minstrumentation, which is responsible for creating operations such as activity, which is the best time to inject our resource class. By tampering with the minstrumentation for our own instrumentationhook, each time we create the activity, it bogus the mresources class as our delegateresources, Each activity that you create later has a resource that understands the plugin, the delegate, and the load Class!
Of course, the above substitutions will be done for the application context.
Programme III:
After packaging, execute a script to modify the resource ID.
Principle:
The resource ID is generated at compile time, its generated rule is the 0XPPTTNNNN,PP segment, is used to mark the APK, by default the system resources PP is 01, the application of PP is 07. TT segment, is used to mark the resource type, the same type of TT value, but the same TT value does not represent the same resource, for example, this compilation may use 03 as the layout of the TT, the next time the compilation may use 06 as the value of the TT, the specific use of that value, is actually associated with the number of resource types used by the current app. NNNN is the resource ID for a resource type, which starts with 1 and accumulates sequentially.
Then we have to solve the resource ID problem, we can start with the value of TT, as long as the TT value at each compile time fixed, can be the resource ID to achieve the effect of grouping, so as to avoid duplication. For example, the host program's layout resource of the TT fixed to 33, the plug-in resource layout of the TT value fixed to 03 (or do not do any plug-in program resource ID processing, so that it uses the compiled native value), you can solve the problem of duplicate resource ID.
The method of fixing the TT value of the resource ID is also very simple, providing a copy of the Public.xml, specifying what type of resource to start in public.xml with what TT value
Another method is to implement grouping by customizing the value of the AAPT at compile time specifying the plug-in's PP segment, overriding the AAPT to specify the PP segment to implement the ID grouping.
Issue 2 How the code loads access
Class is relatively simple to load. Similar to the run-time classpath concept of Java programs, Android's system default ClassLoader Pathclassloader also has a member PathList, as the name implies, it is essentially a list, The runtime looks for classes that need to be loaded from each of the Dex paths in between. Since it is a list, it must be thought, to give it a bunch of DEX paths do not have it? In fact, Google's official launch of the Multidex library is implemented using the above principles. The following code snippet shows the details of modifying the PathList path:
Multidex.java
Private Static void Install(ClassLoader loader, list<file> additionalclasspathentries, File optimizeddirectory) throws Illegala Rgumentexception, Illegalaccessexception, Nosuchfieldexception, InvocationTargetException, NoSuchMethodExcepti on {/ * The patched class loader is expected to be a descendant of * Dalvik.system.BaseDexClassLoader. We Modify its * dalvik.system.DexPathList pathList field to append additional DEX * file entries. */Field Pathlistfield = FindField (loader,"PathList"); Object dexpathlist = Pathlistfield.Get(loader); Expandfieldarray (Dexpathlist,"Dexelements", Makedexelements (Dexpathlist,NewArraylist<file> (additionalclasspathentries), optimizeddirectory));}
Java ClassLoader Basic 1. Basic knowledge of ClassLoader
Both the JVM and the Dalvik load the required classes through ClassLoader, and the ClassLoader load class is often referred to as a parental delegate, and the Classloader.java specific code is as follows:
Java
protected class<?> Span class= "Hljs-title" >loadclass (String className, boolean Resolve) throws classnotfoundexception {class<?> clazz = Findloadedclass (className); if (Clazz = = null ) {try {clazz = Parent.loadclass (className, false ); } catch (classnotfoundexception e) {//Don ' t want To see this. } if (clazz = null ) {clazz = Findc Lass (ClassName); }} return clazz;}
protected class<?> Span class= "Hljs-title" >loadclass (String className, boolean Resolve) throws classnotfoundexception {class<?> clazz = Findloadedclass (className); if (Clazz = = null ) {try {clazz = Parent.loadclass (className, false ); } catch (classnotfoundexception e) {//Don ' t want To see this. } if (clazz = null ) {clazz = Findc Lass (ClassName); }} return clazz;}
From the order of loading classes we can know that LoadClass will first see if this class has been loaded, no, then go to his parent to find, so recursive, called parental delegation.
2. Dynamically Loading Jars
The dynamic loading Jar in Java is relatively straightforward, as follows:
new URL[] {new URL("file:libs/jar1.jar"new URLClassLoader(urls, parentLoader);
Represents the Jar1.jar under load Libs, where Parentloader is the parent in 1 above and can be the current ClassLoader.
3. ClassLoader Isolation Issues
Do you think it's possible for a running program to have two classes with exactly the same package name and class name?
The JVM and Dalvik unique recognition of the class is ClassLoader ID + packagename + ClassName, so there is a possibility that there are two classes in a running program that have exactly the same class name and package name. And if these two "classes" are not loaded by one ClassLoader, it is impossible to convert the example of one class to another class, which is ClassLoader isolation. If you encounter the following exception in Android
java.lang.classcastexception: Android.support .v 4.view can not is cast to Android.support .v 4.view java.lang.classcastexception: Android .support .v 4.view can not is cast to Android.support .v 4.view
When this problem is encountered, it can be passed Instance.getclass (). getClassLoader (); Get ClassLoader to see if ClassLoader is the same.
4. Load public classes in different Jar packages
Now the Host project contains Common.jar, Jar1.jar, Jar2.jar, and Jar1.jar and Jar2.jar all contain Common.jar, we ClassLoader jar1, jar2 dynamically loaded in, which There are actually three copies of Common.jar in Host, such as: Class Diagram
How do we guarantee that Common.jar has only one copy and does not cause the problem of ClassLoader isolation mentioned in 3 above, in fact very simple, there are three ways:
The first kind: we just let the parent of the ClassLoader that loads JAR1 and jar2 be the same ClassLoader, and the ClassLoader is loaded Common.jar, through the above 1 we know that according to the parents, the end will first be Parentclassloader loaded.
The second kind: we rewrite the jar1 and Jar2 ClassLoader, in the LoadClass function we first go to a common.jar containing ClassLoader load can, in fact, the above Parentclassloader Exchange Drop it.
Third: In the generation of JAR1 and jar2 when the Common.jar removed, only one copy of the host, the host ClassLoader for Parentclassloader.
ClassLoader mechanism
The Java Virtual machine loads the data of the description class from the class file into the memory, and the data is checked, transformed and initialized, and finally forms the Java type which can be used directly by the virtual machine, which is the class loading mechanism of the virtual machine.
Unlike the languages in which chained connections work at compile time, in the Java language, the loading, connection, and initialization of types are done during the run of the program, which, while adding some performance overhead to the class load, provides a high degree of flexibility for Java applications. In Java, the language features that can be developed in the same generation are dependent on the dynamic loading and dynamic linking of the runtime. For example, if you write an application that faces an interface, you can wait for the runtime to make the actual implementation class, and the user can use Java with the defined and custom class loaders to let a local application load a binary stream from the network or elsewhere as part of the code at run time. This way of assembling applications is now widely used in Java programs. From the most basic applet,jsp to the sophisticated OSGi technology, the Java language runtime class loaded features are used.
Java class loading is a relatively complex process, which includes five stages of loading, validating, preparing, parsing, and initializing, and for developers, the most controllable is the loading phase, and the loading phase mainly accomplishes three things:
Gets a binary byte stream that defines this class based on the fully qualified name of a class
Converts the static storage structure represented by this byte stream into a runtime data structure in the JVM's method area
A Java.lang.Class object representing this class is generated in memory as a access entry for various data of this class in the method area.
"Get a binary byte stream that describes this class through the fully qualified name of a class" The process is abstracted from the Java ClassLoader module, which is the ClassLoader API in the JDK.
The Android framework provides the Dexclassloader class, which simplifies the process of obtaining a binary byte stream that describes the sub-class by fully qualified name of a class We just need to tell Dexclassloader that a dex file or the path to the APK file will be able to complete the loading of the class. Therefore, the content of this article can be summed up in a sentence:
Tell the plugin's Dex or apk file to "fit" the Dexclassloader, using it to complete the loading of the plug-in class
My QR code is as follows
The QR code of the subscription number is as follows:
Reference
Https://gold.xitu.io/entry/578d184b79bc44005ff029b3
http://www.trinea.cn/android/java-loader-common-class/
http://www.trinea.cn/android/android-plugin/
http://weishu.me/2016/04/05/understand-plugin-framework-classloader/
Http://www.infoq.com/cn/articles/ctrip-android-dynamic-loading
Android Plugin Summary