Ctrip Android App plugin and dynamic loading practice

Source: Internet
Author: User

Ctrip's Android app's plug-in and dynamic loading framework has been on the go for half a year and has undergone initial exploration and continuous polishing, and the new framework and engineering configuration have withstood the test of production practice. This article will detail the principles and implementation details of the Android platform plug-in development and dynamic loading technology, review the architecture evolution of Ctrip's Android app, and expect our experience to help more Android engineers.

Demand-driven

2014, with the business development needs and Ctrip Wireless division, each business Product module attribution to the Business BU, the original Ctrip wireless app development team was divided into the basic framework, hotels, air tickets, train tickets and other development teams, from the development and release of the Ctrip app into a new model. In this mode, the development of communication costs greatly increased, the previous collaborative model is unsustainable, the need for new development models and technology to solve the demand problem.

On the other hand, Ctrip has technically reached the most pit ceiling in the history of Android in 2012 (no one): 65535 method number issues. The old scheme was to put all third-party libraries into the second Dex and use the hack method discovered by Facebook to expand the point Linearallochdr allocation space (5M to 8M), but as the code expanded, the old scheme became increasingly stretched. Dismantling or not dismantling, is not at all possible to consider the problem, continue to split Dex is our only way out. The question is: how can it be smarter to dismantle?

Second, with the impact of organisational restructuring, we have a high level of challenge to our app quality control, and this tension and stress is draining our development team. At this time in addition to drool envy front-end colleagues in the online update of the ability to continue to release, there is no way to solve the native architecture of this fundamental flaw? No! The additional benefit of plug-in dynamic loading is the client's thermal deployment capability.

From the fundamental requirements above, it can be seen that the plug-in dynamic loading architecture scheme will bring us tremendous benefits, in addition to many benefits:

    • Compile speed boost

      After the project was split into more than 10 sub-projects, the Android Studio compiler process cumbersome shortcomings were rapidly amplified, the Win7 mechanical hard disk development machine on the compilation time has exceeded 1 hours, the outrageous turtle speed compiler let developers complain incessantly (of course, now MAC+SSD too much faster).

    • 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

List of so many pain points, children's shoes have long been a surge of emotions, right? To get started, plug-in dynamic loading architecture exploration is starting.

Principle

On the idea of plug-in, the software industry has enough user education. Whether it is the daily use of the browser, or accompany the programmer countless day and night eclipse, and even QQ behind, there are plug-in technology support. We want to plug-in on Android, there are 2 main issues to consider:

    • Compile time: Compilation of resources and code

    • Runtime: Loading of resources and code

Solve the above 2 key issues, then how to implement the plug-in specific interface, it becomes personal technology preferences or specific requirements of the scene differences. Now we have to solve the above key issues, one of the most troublesome is the compilation and loading of resources issues.

How is Android compiled?

Let's start by looking at how Android is compiled. Please see:

The whole process is huge and complex, and we focus on several key links: aapt, Javac, Proguard, Dex. The input and output involved in the relevant links are highlighted on the map.

Compilation of resources

Android Resource compilation relies on a powerful command-line tool: AAPT, which is located <SDK>/build-tools/<buildToolsVersion>/aapt , has a number of command-line arguments, several of which deserve our special attention:

    • -I add an existing package to base include set

      This parameter appends an already existing package to the dependent path. In Android, the compilation of resources also need to rely on, the most common dependency is the SDK comes with the Android.jar itself. Open Android.jar can be seen, in fact, is not a common jar package, which not only contains the existing SDK class library class, but also contains the SDK's own compiled resources and the Resource Index table RESOURCES.ARSC file. In the daily development, we also often use the @android:color/opaque_red form to refer to the SDK to bring resources. All of this comes from the AAPT reference to Android.jar during compilation. Similarly, we can also use this parameter to refer to an existing APK package as a dependent resource to participate in the compilation.

    • -G A file to output proguard options into.

      In resource compilation, the class name of the component, the method reference causes the run-time reflection call, so this type of symbolic amount cannot be confused or cut off during the code obfuscation phase, otherwise the class and method referenced in the layout file cannot be found at run time. The-G method exports the classes and interfaces that must be keep discovered during resource compilation, and it participates as an append configuration file in the late stage of the obfuscation.

    • -J specify where to output R.java resource constant definitions

In Android, all resources generate the corresponding constant ID at the Java source level, which is recorded in the R.java file and participates in the subsequent code compilation phase. In the R.java file, the Android resource generates an ID for all resources during compilation and is uniformly stored as a constant in the R class for other code references. Each int type four-byte resource ID that is generated in the R class is actually made up of three fields. The first byte represents the package, the second byte is the classification, and the three or four bytes is the ID within the class. For example:

``` java//android.jar中的资源,其PackageID为0x01public static final int cancel = 0x01040000;//用户app中的资源,PackageID总是0x7Fpublic static final int zip_code = 0x7f090f2e;```

After we modify the AAPT, we can assign a different head byte PackageID to each of the resources in the child apk, so that it does not conflict with each other.

Compilation of code

You should be very familiar with the Java code compilation, only need to pay attention to the following issues:

    • Classpath

      Java source code compilation needs to gathered up all dependencies, classpath is used to specify which directories, files, jar packages to find dependencies.

    • Confuse.

      For security purposes, most Android projects will be confused. The principle and configuration of confusion can be consulted in the Proguard manual.

With this background knowledge, we can consider and design the basic principles and main processes of the plug-in dynamic loading framework.

Realize

Implementations are divided into two categories: 1. Build process transformation for plug-in sub-engineering, 2. Runtime dynamic load Transformation (host program dynamic loading plug-ins, there are two barriers to breakthrough: how resources are accessed, how the code is accessed).

Plugin Resource Compilation

, we need to take into account the following points for the compilation of the plugin's resources:

    • Use -I parameters to reference the host's apk.

      As a result, the resources and controls, layout classes of the host can be used in the resource and XML layout of the plug-in.

    • Add parameters for Aapt --apk-module .

      As mentioned earlier, the resource ID actually has a packageid internal field. We specify a unique PackageID field for each plug-in project, which is easy to identify based on the resource ID, which needs to be found and loaded from the plugin apk. Further elaboration will be presented later in the Resource loading section.

    • Add parameters for Aapt --public-R-path .

      Referencing a system resource uses the fully qualified name of its R class to refer to the specific ID in accordance with the general means used by the resource in the Android.jar package to differentiate it from the android.R R class in the current project. The plug-in's resource references to the host, of course, can also be used base.package.name.R to complete. But for historical reasons, the "plug-in" code of each BU is decoupled from the main app, resource references or direct use of the current project R. If you change to standard mode, you will need to change the current large number of legacy code to R be base.R large and error-prone, and the future use of BU developers is a bit less "transparent". So we made concessions in the design, additional --public-R-path parameters, for AAPT indicated base.R the location, let it during the compilation of the base resource ID defined in the plug-in R class full copy, so that the plug-in project can be the same as before, do not care about the resources from the host or itself, You can use it directly. Of course, the side effect of this is that the host and plug-in resources should not have the same name, which we are constrained by the development of norms, relatively easy to understand some.

Plug-in Code compilation

The following points need to be considered for code compilation for plug-ins:

    • Classpath

      For plug-in compilation, in addition to Android.jar and the third-party libraries that you need to rely on, you also need to rely on the host-led Base.jar class library. There is also a requirement to confuse the host: All public/protected of the host may be dependent on the plugin, so these interfaces are not allowed to be confused.

    • Confuse.

      Plug-in project in the confusion, of course, the host's confusion after the jar package as a reference library import.

Since then, all the important steps in the compilation of the technical solution have been determined, the rest of the work is simply to import the plugin apk into the first step to build a good base.apk and re-sign the alignment.

All you have to do is show. Let's take a look at how the plug-ins went on stage at runtime.

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. */public abstract AssetManager getAssets();/** Return a Resources instance for your application‘s package. */public abstract Resources getResources();

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

private final Resources mResources;@Overridepublic AssetManager getAssets() {   return getResources().getAssets();}@Overridepublic Resources getResources() {   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}*/public final int addAssetPath(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.

Load of the run-time class

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 IllegalArgumentException, IllegalAccessException,             NoSuchFieldException, InvocationTargetException, NoSuchMethodException {    /* 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,         new ArrayList<File>(additionalClassPathEntries), optimizedDirectory));}

Of course, for different Android version, the class loading way slightly different, you can refer to Multidex source code to do the specific difference processing.

At this point, the four fundamental questions that have been raised before have already been solved in concrete solutions. The rest is coding!

The coding is mainly divided into three parts:

    • Modifications to the AAPT tool.

    • Gradle the implementation of the packaged script.

    • The implementation of the run-time load code.

Specific implementations can refer to our Open source project dynamicapk on GitHub.

Benefits and costs

Everything has its two sides, especially like the dynamic loading of the use of unofficial hack technology, but also in the planning stage to consider the benefits and costs clearly, easy to complete after the re-disk.

Income
    • The plug-in architecture adapts to the existing organization structure and the development rhythm demand, the BU not only from the code level, but also from the project control level to achieve the cohesion poly low coupling, greatly reduced the communication cost, improved the work efficiency.

    • After splitting into multiple small plug-ins, Dex then said goodbye to the number of ceilings.

    • Hotfix for the app quality to do a final layer of protection, no irreparable loss, and now hotfix level granularity controllable, that can be the traditional class level (directly using the Pathclassloader implementation), can also be a resource apk level.

    • Abtesting from the old ugly if/else realization, multiple sets of options to choose to load on demand.

    • The compilation speed is greatly improved, the BU only need to use the host's compilation results update to compile their own sub-engineering parts, minutes.

    • App hosting apk greatly reduced, each business module on demand background load or lazy load delay, start speed optimization, farewell black screen and start ANR.

    • Each BU plugin apk independent, who fat who skinny at a glance, app size control targeted.

The above revenue, basically achieve or exceed the project's expected target: D

Price
    • Resource aliases

      Android provides a powerful resource alias rule, reference can get more detailed description. Unfortunately, using resource aliases on some models, such as Samsung S6, can lead to problems where resources cannot be found because of confusion in the host resource and plug-in resource IDs. Helpless can only prohibit the use of this technology, fortunately, the abandonment of this advanced features will not cause a fundamental loss.

    • Duplicate Name resource

      As explained earlier, the host's resource ID is fully duplicated in the plug-in. Without the protection of the namespace of the package name, a resource with duplicate names can directly cause conflicts. Temporarily through the way of naming norms to circumvent, good naming habits are also the development should be done, so the cost of the solution is small.

    • Enumeration

      Many controls use enumerations to constrain the range of values that a property can take. Unfortunately, the Android enumeration is actually named to uniquely determine the ID constants generated in R, with no namespace or owning control. Because of the same reason, an enumeration with the same name inside the host and plugin can cause an ID conflict. Temporarily also by naming the standard way to evade.

    • External access to resource capabilities.

      For a very small number of applications that require external access to the APK resource (for example, sending a delay notification), the app has not started yet, and the resource acquisition is done by the system, and it is no longer obvious that the internal plug-in's resource location and access method is available. There is no room for such a situation, but special permission is given for such resources to be placed directly in the host APK.

These costs, or harmless, or the cost of alternative solutions are very low, are within acceptable range.

Future optimisation

There are some advanced features, because the priority relationship is not implemented yet, but as the development requirements for each line of business are also mentioned on the optimization schedule, such as:

    • Plug-in engineering supports so libraries.

    • The plug-in project supports various advanced dependency features such as Lib engineering dependencies, AAR dependencies, and maven remote dependencies.

    • IDE-friendly, so developers can more easily build plug-in apk.

Open source

After the above introduction, I believe you have a preliminary understanding of Ctrip's Android plug-in development and dynamic loading scheme. For details, please visit GitHub Open source project dynamicapk. Ctrip Wireless basic research and development team will continue to work hard to share more project practice experience for you. Welcome to the Ctrip App team's public number: Ctripmobile.

Ctrip Android App plugin and dynamic loading practice

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.