1 background
It is recommended to read the Android Studio starting to master and Groovy Scripting Basics complete Guide and Gradle Scripting Basics Complete Guide three blogs as background knowledge, so as to better, more systematic string together. The core of this article is the following:
This article will not give you too much information about Gradle’s Android plugin. For details, see the documentation API and Gradle Configuration. In fact, the personalized build configuration is usually written by Gradle and Groovy, which has little to do with Android plugin. So the focus is still on Groovy and Gradle builds.
Before you build, however, you need to understand some of the build process and related IDE and compilation features, as described below.
The workman is like waterblog.csdn.net/yanboberNo reprint without permission, please respect the author’s work.Contact me in private】
2 Android application compilation framework
When developing apps, most of the compilation process is directly through the IDE button or command line to generate APK in one step. Intuitively, it seems that the source code to generate APK is only one step, but this is not the case. The process from the moment we click the button to the generation of apK is actually quite complex and involves many steps, so let’s take a quick look.
2-1 Android application source code to generate Apk process
Android app compilation is packaged as a.apk file, which is essentially a zip package (you can rename the suffix to extract it, for example). The compressed package contains at least a. Dex file compiled as a. Class file, a binary Androidmanifest.xml file, a compiled resource file resources.arsc, an uncompiled resource file, etc., and then signs the compressed package before running it. The specific process is as follows:
The Android build system is used to build, test, operation and encapsulation application a kit, we can have the whole building system integration OK AS or use the command line, build process involves many tools and processes, through these tools and processes to generate a lot of intermediate files, then the resulting APK. The following diagram depicts the different tools and processes involved in the build process:
The build system combines “Product Flavors”, “Build Types”, and “dependencies” of all resources. If the resources in different folders have the same name or Settings, they are overwritten as follows: Dependencies overlay build types, Build types overlay Product flavors, and Product flavors overlay the main resource folder. Here is a detailed description of the typical build process shown above:
-
The Android Resource Packaging tool (AAPT) compiles the application’s resource files (such as androidmanifest.xml and activity-related XML files, etc.) and generates an R.java file that is the basis for our Java code and resource files.
-
The AIDL tool converts all. Aidl files in the application to Java interfaces.
-
The Java compiler compiles the output of all Java code in the application (including R.Java and aiDL interfaces) into class class files.
-
The dex tool converts the class files (including third-party JAR packages) generated by application compilation into Dalvik bytecode, and.dex files can be packaged as.apk files.
-
The ApkBuilder tool packages all non-compiled resources (such as images), compiled resources, and DEX files into one APK file.
-
Once the.apk file is generated, it must be signed (debug or Release signature) to run on the device.
-
Align APK with zipalign tool to reduce memory footprint when APP runs on device.
By default, everything generated during the entire build process is in the app/ Build directory (both intermediate and final products).
Special note: Application builds have a 64K method limit statement, exceeding 64K will throw the following build information:
Unable to execute dex: method ID not in [0, 0xffff]: 65536.Copy the code
If you run into this problem, please refer to me to solve it.
The following figure shows the detailed process of building and compiling the entire Android application (excluding NDK) (official source) :
It is clear from this diagram that the process of compiling the source code of an Android application into the final APK production is quite complicated. We usually just hand these details over to the IDE and build framework, so we don’t notice these details.
2-2 Main tools related to Android application compilation process
The above briefly describes the process of compiling framework from source code to APK. The following briefly describes several important compilation tools involved in this process.
The 2-2-1 aapt tool
Aapt (Android Asset Packaging Tool) is an Android resource Packaging Tool. In the Tools directory of the SDK, you can use aAPT to view, create, and update ZIP files (such as ZIP, JAR, and APK) and compile resource files into binary files. We rarely use this tool directly, but as shown in the previous compilation flowchart, the compilation framework automatically helps us to deploy the tool. Here is what happens when the aapt command is configured with OK:
As for the usage of aapt command tools, we can directly enter aapt in the terminal and you can see the relevant help document. Here we only give a few of our more commonly used commands, and the rest refer to the help document.
#aapt l[ist] [-v] [-a] file.{zip,jar,apk}
#aapt d[ump] file.{zip,jar, APK}
This command is useful. Sometimes, you can use this command to quickly obtain information such as the package name of an APP.
Aapt Other operation command parameters
Aapt command can also be used to package and generate compressed resource packages, delete compressed resource packages or add specified files, which is also the core tool command used in the compilation and construction system to generate processes such as R. Java. If you are interested, Google can manually package resource files through the aapt command line.
The 2-2-2 aidl tool
AIDL (Android Interface Definition Language) is an IDL Language used to generate code that can communicate between two processes (IPC) on Android devices. If you want to call an object from another process in one process, you can use AIDL to generate serializable parameters for passing. We usually write AIDL files according to AIDL rules during development. However, we find our AIDL Java interface files in the build directory. This is because the compilation framework uses the AIDL compilation tool to convert.
Here is the aiDL tool for converting aiDL files into Java files in the TOOLS directory of the SDK:
The use of aiDL tools is very simple, the help documentation is very clear, detailed interested in their own to try, here is no longer detailed explanation; I don’t really use it manually. I haven’t really studied it.
The 2-2-3 dx tool
We use AAPT to package resources and generate R.Java at the same time, compile the AIDL file to generate the corresponding Java file through AIDL, and compile r.Java, Java source file and AIDL Java file into the relevant class file through Java compiler. For pure Java, class bytecodes are executable files for the JVM. However, for The Android Dalvik and ART virtual machines, class files cannot be executed directly. So we need to compile the class bytecode into the dex executable file using the dx tool in the SDK/tools directory. The following is the basic situation of dx tool commands:
When it comes to the DX tool, we have to emphasize a few more important concepts and fundamentals, as detailed below.
File relationship between apk, dex, and odex:
Dex, the full name for Dalvik VM Executes (an Android Dalvik executable that ART continues to embrace), and files in the dex format are often optimized for execution in Android virtual machines and typically become larger than the original dex file. This optimization occurs in two ways:
-
Preset application: Optimized files with the suffix odex are generated directly after the system is compiled, and dex is not unpacked when the app is started, which is efficient. Therefore, an APK file without the dex file and an odex file are displayed when the preset application is published.
-
Non-preset applications: ApK files containing dex files are generated directly by compilation. The dex files contained in apK files are optimized at runtime, and the optimized files are stored in the cache.
This is why the system will see odex and APK files without dex after compiling the source code of the preset app, and only see apK files containing dex after compiling the independent app. Someone once had this doubt when doing box development in last company before, of course I also had!
Dex file 65535 Abnormal method Limit Cause:
The Android Dalvik and ART runtime environments can execute the.dex file generated by the DX tool, which means that Dalvik and ART use the same set of Dalvik instructions. According to relevant data query, Dalvik instruction set uses 16-bit registers to store all method references in the project. 2 to the power of 16 is 65536, that is to say, a DEX file can only reference 65536 methods at most. Therefore, Dalvik and ART run time environment have this limitation. Oh my god!! Isn’t that what we sometimes compilation of project throws Android Dex method limits the cause of the abnormal yao (it also has introduced, don’t understand the on going back to see, that is to say, compile time throw this exception because caused by the method of project contains too much, but official Google also aware of the defect, so their solutions are given, as follows:
-
Use ProGuard to remove useless methods in the project, and use related scripts to remove methods in third-party libraries that are not used in the project;
-
Since the Dalvik runtime environment restricts an APK to only one classes.dex file, we can use the Multidex Support Library to Support multiple. Dex files in an APK, thus breaking the 65536 limit.
This is a classic error in the dx process, and it usually occurs when using a lot of third party libraries, so it needs to be looked out for.
The 2-2-4 apkbuilder tools
The apkBuilder tool is actually a bit outdated because it has been removed from newer SDK versions, But the essence of the apkbuilder tool is to/android SDK – Linux/tools/lib/sdklib jar ApkBuilderMain etc in a wrapper, so even in the absence of the tool we can achieve encapsulation, However, the new compilation framework will help us solve this process automatically, so we don’t have to do it manually. The essence of this process is similar to that of a compression tool, except that it packages related resources, DEX files and so on into an APK file that specifies the compression method and depth.
2-2 2-5 KeyTool and Jarsigner
The essence of signing apK packaged and compressed by ApKBuilder is to write specific tag information in specific fields of the application to indicate that the software has been approved by the signer. The signature is used to identify the author of the application, check whether the application has changed, and check whether the application is the same.
Generally, you can use the keytool to generate a signature private key, and then use the Jarsigner tool to sign the application using the private key. But the process is very simple, so without further ado, imagine.
In 2-2-6 the zipalign tool
Zipalign tools optimize packaged applications for maximum efficiency and use less Random Access Memory (RAM) at runtime. Zipalign aligns the data in apK files with 4 bytes, which means that the compiler operates on 4 bytes as a unit so that the CPU can access the code efficiently, because the Android system can read the file by calling the Mmap function. In that process can be like a read/write memory we ordinary apk file operation, so when the alignment of the application in the system is executed through Shared memory read IPC resources can get high performance, if there is no alignment process must display the dispatching the read method to manipulate data, such as process that is running will be slow and spend more memory, Performance deteriorates.
The use of the Zipalign tool is no more verbose here, as compilation frameworks often allow you to configure scripts directly without having to execute commands manually.
The 2-2-7 ProGuard tools
ProGuard is a tool for compressing, optimizing, and obturating Java bytecode class files. It removes useless classes, fields, methods, properties, and comments to maximize class bytecode file optimization. It can also rename existing classes, fields, methods, and properties with short, meaningless names. We often use it to confuse the final project and make it slightly harder to decompile. Of course, decompile is no longer an issue with today’s technology, but instead focus on optimizing useless resources and simple alternatives.
The use of the ProGuard tool is no more verbose here, as compilation frameworks often allow you to configure scripts directly without having to execute commands manually.
The 2-2-8 jobb tools
In fact, this tool is not part of the normal compilation framework process, is an extension of Android features. From Android version 2.3, the system adds an OBB file system (access restriction isolation file system) and StorageManager class to manage data security on external storage.
If you’ve ever installed a Monument Valley or Machinarium game on an Android phone, you’ll have a good idea of the joBB tool and OBB file system here. Do you remember that after installing a game that is tens of megabytes in size you need to download a 200-megabyte ZIP package to the Android/obb/[GamePackageName] directory on your filesystem to play the game? The reason for this is that our game project contains a large number of resources (images, videos, music, etc.), which can be hundreds of megabytes directly compiled into APK, and the system has a limit on the size of APK files when installing APK. Such a large APK file will definitely cause the Android system to not install APK properly. I’m sure you’re smart enough to say, why don’t we just put these resources on the SD card? Ha ha, you want to have you thought about a problem, if directly into the SD card, music, video, images and other manager can not directly index to these things, that much is not good (interrupt, can also be the suffix to save the resources, so the library can’t index, such as Android E-mail application of attachments is so of the design, Clever!) . Fortunately, Android 2.3 OBB files are a great way to solve these problems.
In this case, the OBB file system must require that files be stored in a certain format, and Jobb is a tool to solve this problem. Jobb allows us to generate encrypted or unencrypted extension files in OBB format. OBB files can be used as extended resource files for Android applications, independent of APK files. Here is the documentation for the jobb tool:
I don’t want to go into detail about the Jobb tool here, but it’s not too late to think about it when you’re developing big resource applications like games, just know it’s there.
2-3 Android app build Jack and Jill new toolchain
Now that we have a good understanding of the general application compilation framework, But the question is, do you also feel that the current Android build process is quite painful (compilation and construction is extremely slow), in fact, Google officials seem to be aware of this problem, They also gave some optimizations for the current stage at this year’s Google IO Conference. One of the highlights that is worth trying and mentioning is the two new compilers Jack and Jill (currently officially claimed to be Experimental compiler, not robust enough, still in the bug collection stage, currently does not support annotation processing). Java 8, etc., so be careful), the two compilers are meant to simplify the android build process, which is basically an attempt to speed up the build process. Here’s a look at the build process using the Jack and Jill compilers:
As you can see, Jack is a tool based on the Java compiler and ProGuard, but the current version does not support some of ProGuard’s advanced features (such as removing logging code). Jill converts Java library bytecode into jayCE intermediate bytecode. Jack files, jack compiles Java source code and JayCE bytecode to generate optimized DEX bytecode.
To try Jack and Jill, make sure your Build Tools version is 21.1.1 or higher. Gradle configuration is as follows:
android { ... BuildToolsRevision '21.1.2' defaultConfig {// Enable the experimental Jack build tools. useJack = true}... buildToolsRevision '21.1.2' defaultConfig {// Enable the experimental Jack build tools. useJack = true}... }Copy the code
In a word, I’m still young now, so I have to wait and see what I can achieve. I have to see the trend behind it. Anyway, I didn’t use him at present.
The workman is like waterblog.csdn.net/yanboberNo reprint without permission, please respect the author’s work.Contact me in private】
3 Android application IDE and compile related features
Here are some of the most efficient coding features for IDE development, as well as some compile-related considerations, as described below.
3-1 Android Application JAR package and AAR package
When we compile a library of our own in Android Studio, we generate both jar and AAR packages. Their specific path is as follows:
Package type | Output path in AS |
---|---|
jar | /build/intermediates/bundles/debug[release]/classes.jar |
aar | /build/outputs/aar/library.aar |
The difference between the two is as follows:
Package type | describe |
---|---|
jar | Contains only class files, not resource files, for libraries written in pure Java. |
aar | Contains all the class and RES resources, like the UI library. |
In fact, the difference between them can be seen intuitively by decompression, which is not described here.
About the Android compilation framework also need to know a useful tool in the attribute, that is the tools namespace attribute, his namespace URI is schemas.android.com/tools, say this namespace is specially designed for developers, effective only at the design stage and operation stage is invalid.
.Copy the code
Tools attributes replace all Android attributes and are only valid at design time and are not carried into the final APK, so they are not valid at runtime. The entire Tools namespace has two main categories of properties, lint-specific and design-specific. Let’s list some of the useful attributes associated with Tools.
Tells Lint to ignore certain warnings in XML. Usage:
AllCopy the code
Used to specify the API level, similar to the @targetAPI annotation in a Java file, with an integer value or meaning string. Usage:
Copy the code
By default, strings in the res/values/strings. XML file will be spell-checked and will be warned if the native language is not English. We can specify the native language this way and ignore the warning. As follows:
Copy the code
This attribute is actually the associated Activity attribute. After adding this attribute to the XML file, you can preview the XML file to know which theme is used for preview. At the same time, you can associate the Activity file with the XML file, and jump to the index directly from the Java file. As follows:
Copy the code
This property is used in the FRAGMENT node of the XML to tell the IDE at development time what the fragment looks like in preview mode. As follows:
Copy the code
You can obviously guess the preview item and header used to specify the ListView, AdapterView, GridView, and ExpandableListView. As follows:
Copy the code
This property is set to the root node of an included layout and is available for preview. As follows:
Copy the code
Used to tell the IDE that the current XML layout displays the specified Menu style during preview. In fact, if we specify tools: Context, the IDE will be smart enough to look for the Menu style preview in the onCreateOptionsMenu method in our specified Activity file. Of course, we can override the Menu preview in our Activity with this property. As follows:
Copy the code
Specifies the preview mode for the ActionBar. The options are “standard”, “list”, or “tabs”. As follows:
Copy the code
3-2-11 Designtime Design-time attributes
Tools attributes replace all Android attributes and are only valid at design time and are not carried into the final APK, so they are not valid at runtime. For example, when we write a TextView and don’t want to give it the initial text content in XML, but want to preview it, we can use the Tools attribute instead. As follows:
Copy the code
As you can see, the Tools namespace attributes speed up the flexibility and predictability of our development, while ignoring these attributes in the compilation framework and not carrying them into the final product APK. We can use these attributes at our discretion during development.
Annotations 3-3 Android Annotations
In version 19.1 of the Android Support Library, a new annotation package has been added. This package is used to annotate code to catch bugs and problems in applications. The code in this package already uses this annotation, and 13 new annotations have been added in version 22.2. These comments can facilitate our code development and distribution specifications and bug check, the specific usage will be explained below.
Annotation Library relies on references
The Annotations package is not automatically included by default, but it is if you use the AppCompat package, which uses annotations.
Add the following annotations to the Android project Gradle file:
Dependencies {the compile 'com. Android. Support: support - annotations: 22.2.0'}Copy the code
If you do not want to use this annotation package in the Android project, you can write it as follows (the URL is the local Android SDK annotation package path) :
repositories {
jcenter()
maven { url '/extras/android/m2repository' }
}Copy the code
3-3-2 performs annotations
When we pass an error type parameter to an annotated method using Android Studio and IntelliJ, the IDE flags the error in real time. If you are using Gradle version 1.3.0 or later and have Android M Preview Tools installed, you can check this by calling Gradle’s Lint task from the command line (nullness annotations are ignored).
3-3-3 Null Null type judgment annotation
The @nullable annotation is used to indicate that a given parameter or return value can be NULL. The @nonNULL annotation is used to indicate that a given parameter or return value cannot be NULL.
If a local variable has a null value and is passed AS an argument to a method whose argument is annotated by @nonNULL, AS will alert you to a potential crash. As follows:
import android.support.annotation.NonNull; import android.support.annotation.Nullable; . /** * Add support for inflating the tag. */ @Nullable @Override public View onCreateView(String name, @NonNull Context context, @NonNull AttributeSet attrs) { ...Copy the code
3-3-4 Resource type annotations
Android resource values are usually associated with an integer ID mapped from an R file. This means that taking a layout resource parameter can easily be passed a different type of resource parameter because they are all integer resource ids and the compiler can’t tell them apart. To solve this problem, use resource type annotations because annotations provide type checking. For example, if an integer argument annotated by @layoutres passes a string resource argument, the IDE will give an error message:
The setContentView method was passed with an error:
SetContentView resource annotation
There are actually many different resource type annotations, For example, @Animatorres, @animres, @anyres, @ArrayRes, @attrres, @Boolres, @colorres, @dimenres, @drawableres, @Fractionres, @idres, @intege RRes, @interpolatorres, @layoutres, @menures, @Pluralsres, @rawres, @stringres, @styleableres, @styleres, @xmlRes, etc. Typically, the corresponding resource type annotation for a resource of type foo is @foores. In addition, there is a special resource type annotation named @anyres, which is used to annotate a resource of an unknown special type and must be a resource type. Such as Resources. GetResourceName (@ AnyRes int resId) on use, We can use getResources().getResourcename (r.rawable.icon) and getResources().getResourcename (r.string.app_name). It cannot be used with getResources().getResourcename (42).
3-3-5 IntDef/StringDef type annotation
This type of annotation is based on Intellij’s magic number checking mechanism, because many times in Android development we use integer constants instead of enumerated types for performance reasons. Take an example from the AppCompat library:
import android.support.annotation.IntDef; . public abstract class ActionBar { ... @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS}) @Retention(RetentionPolicy.SOURCE) public @interface NavigationMode {} public static final int NAVIGATION_MODE_STANDARD = 0; public static final int NAVIGATION_MODE_LIST = 1; public static final int NAVIGATION_MODE_TABS = 2; @NavigationMode public abstract int getNavigationMode(); public abstract void setNavigationMode(@NavigationMode int mode);Copy the code
The unannotated part above is the original code and API, we created a new annotation NavigationMode with @interface, and we labeled it with @intdef to indicate its possible values, The @Retention(retentionPolicy.source) addition tells the compiler that this newly defined annotation does not need to be recorded in the generated.class file; After using this annotation, the IDE will give an obvious error if we return or pass a parameter that is not in the specified constant value.
We can also specify the integer constants for the nature of a tag type, because it can |, & operator at the same time passing multiple integer constants. Here’s an example:
@IntDef(flag=true, value={
DISPLAY_USE_LOGO,
DISPLAY_SHOW_HOME,
DISPLAY_HOME_AS_UP,
DISPLAY_SHOW_TITLE,
DISPLAY_SHOW_CUSTOM
})
@Retention(RetentionPolicy.SOURCE)
public @interface DisplayOptions {}Copy the code
@stringdef does basically the same thing as @intdef except that it works on strings. I’ll get more information on type annotations.
3-3-6 thread annotations @UithRead, @workerThread, etc
Thread annotations are only supported in Support Library 22.2 and later. If our methods can only be called in a specified thread type, we can annotate them with the following four annotations:
-
@UiThread
-
@MainThread
-
@WorkerThread
-
@BinderThread
You can annotate a class itself if all its methods have the same threading requirements.
An example of the use of thread annotations is AsyncTask, as follows:
@WorkerThread
protected abstract Result doInBackground(Params... params);
@MainThread
protected void onProgressUpdate(Progress... values) {
}Copy the code
An error is reported if the annotation thread is not executed when using this method, as follows:
3-3-7 constraint values annotation @size, @intrange, @floatrange
If our arguments are of type float or double and are limited to a range, we can use the @floatRange annotation as follows:
Public void setAlpha(@floatRange (from=0.0, to=1.0) float alpha) {public void setAlpha(@floatrange (from=0.0, to=1.0) float alpha) {Copy the code
If our argument is int or long, we can use the @intrange annotation to constrain the range of values, as follows:
Public void setAlpha(@intrange (from=0,to=255) int alpha) {... }Copy the code
For collections of data or strings, we can use the @size annotation to limit the collection Size or string length. Such as:
@Size(min=1)
@Size(max=23)
@Size(2)
@Size(multiple=2)Copy the code
RequiresPermission 3-3-8 permissions annotation @requiresperMission
If our method calls require specific permissions, it can be annotated with @RequiresperMission. As follows:
@RequiresPermission(Manifest.permission.SET_WALLPAPER)
public abstract void setWallpaper(Bitmap bitmap) throws IOException;Copy the code
The anyOf attribute can be used if the method requires at least one of the permissions set. As follows:
@RequiresPermission(anyOf = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION})
public abstract Location getLastKnownLocation(String provider);Copy the code
The allOf attribute can be used if the method requires multiple permissions at the same time. As follows:
@RequiresPermission(allOf = {
Manifest.permission.READ_HISTORY_BOOKMARKS,
Manifest.permission.WRITE_HISTORY_BOOKMARKS})
public static final void updateVisitedHistory(ContentResolver cr, String url, boolean real) {Copy the code
Permissions for an Intent can be specified directly on the defined Intent constant string field (which is usually noted by the @sdkConstant annotation). As follows:
@RequiresPermission(android.Manifest.permission.BLUETOOTH)
public static final String ACTION_REQUEST_DISCOVERABLE =
"android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";Copy the code
Sometimes the permissions for ContentProvider may require separate annotation Read and Write permissions, so you can annotate with @read or @write. As follows:
@RequiresPermission.Read(@RequiresPermission(READ_HISTORY_BOOKMARKS))
@RequiresPermission.Write(@RequiresPermission(WRITE_HISTORY_BOOKMARKS))
public static final Uri BOOKMARKS_URI = Uri.parse("content://browser/bookmarks");Copy the code
The 3-3-9 override method annotation @callsuper
You can use the @callsuper notation if you want to call a super method of the parent class in an override method. As follows:
@CallSuper
protected void onCreate(@Nullable Bundle savedInstanceState) {Copy the code
@checkResult, @Visiblefortesting, @keep
If our method returns a value and expects the caller to do something with that value, we can annotate it with the @checkResult annotation.
If we want to use a class, method, or field for testing, we can use the @VisibleForTesting annotation to indicate that.
In particular, we have added the @keep annotation to the annotation library, but the current version of the Gradle plugin does not support it very well, so the annotation will not be confused.
3-3-11 Other notes relevant
If we use these annotations in our lib library and create aar packages from a Gradle build, the Android Gradle plugin extracts the annotation information and places it in the AAR file for use in the library at build time. In the AAR file, you can see a file called Annotations. Zip that records annotations in XML format using IntelliJ annotations.
PS, IntelliJ actually has its own annotations, which I won’t elaborate on here.
As you can see, this annotation makes our IDE look smarter, more powerful, and helps our compilation framework detect problems early, and provide warnings or errors.
The workman is like waterblog.csdn.net/yanboberNo reprint without permission, please respect the author’s work.Contact me in private】
4 Gradle Android build
There’s not much to say about Android Plugs, just take a look at The Groovy syntax and Gradle framework and check out Gradle Android Plugs for DSL features, then check out the API and Android DSL rules as you go. See section 7 of Android Studio from Getting Started to Mastering for an example of a common template.
4-1 Gradle Android builds the configuration foundation
The Android Studio project contains a file called build.gradle at the root of the project and at the root of each module. In most cases, we can do this by simply modifying the build.gradle file in the related Module. Here’s an example:
apply plugin: Application 'android {compileSdkVersion 19 buildToolsVersion "19.0.0" defaultConfig {applicationId "Com.example.my. app" minSdkVersion 8 targetSdkVersion 19 versionCode 1 versionName "1.0"} buildTypes {release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard - rules. Pro' dependencies}}} {the compile project (" : the lib "), the compile 'com. Android. Support: appcompat - v7:19.0.1' compile fileTree(dir: 'libs', include: ['*.jar']) }Copy the code
At some point you will find repositories declared twice in your Gradle script.
The repositories declaration in the BuildScript block: This declaration declares the resources (dependencies, third-party plug-ins, Maven locations, etc.) that the Gradle scripts themselves need to use.
A declaration in the build.gradle file: This declaration is a repository declaration for the project itself.
If we want to use third-party plug-ins in Gradle scripts, and these plug-ins and libraries are not used in our project, but support other Gradle scripts to run, we should put this dependency declaration in the BuildScript code block. Gradle executes scripts first and then executes the rest of the script. In contrast, if we need to use plug-ins or libraries in our project, we need to define them in dependencies outside of the BuildScript block.
4-2 Gradle Android builds its configuration
Let’s take a look at how you can build multiple versions of a project using Gradle build system (for multiple device types, different app Market releases, etc.). This build function is simple, powerful, and useful.
The steps for creating multiple VERSIONS of APK using Product Flavors are as follows:
- Define product Flavors in the build file;
- Create additional resource directories for each flavor.
- Add these resources to the project for type-specific compilation;
To start with the first step, define the compile configuration for the two types as follows:
. android { ... defaultConfig { ... } signingConfigs { ... } buildTypes { ... } productFlavors {demo {applicationId ". Com. Buildsystemexample. App demo "versionName" 1.0 demo} "full {applicationId "Com. Buildsystemexample. App. Full" versionName "1.0 - full"}}}...Copy the code
The above example creates two APKs with ids different from version; In particular, attribute elements with the same product flavors are defined in the defaultConfig element, because the attribute values of the defaultConfig element are applied to all build Variants by default. Unless we override these values in build Variant.
Next, we looked at steps 2 and 3, adding different resources for each flavor. As you can see from the previous step, we defined different applicationids. The main difference is demo and full. This means that we can create resource directories for both cases in the SRC directory (for example, demo and full). We’ll put some specialisation resources for Demo and Full) and when we’re done we’ll just choose the different types of Build Variants from the AS panel.
4-3 Gradle Android Plugin DSL
Google official and Gradle official have a detailed description of Android DSL, heart is very tired, please allow me to fake a time.
The workman is like waterblog.csdn.net/yanboberNo reprint without permission, please respect the author’s work.Contact me in private】
5 Summary of Android application compilation
This blog is a difficult labor, the draft box sleep for one or two months, finally born today. It’s been on and off. It’s depressing.
Above we introduced the Android application source code generation Apk process and related tools involved, but also introduced the application of new compilation tools Jack and Jill, The Gradle Android Plugin is a DSL specification for Android Annotations. The Gradle Android Plugin is a DSL specification for Android Annotations. The Gradle Android Plugin is a DSL specification for Android Annotations. Understanding these processes and simple principles will be essential for application development and construction.
Generally speaking, this article is difficult to deliver, the quality is not high, make do with it!
The workman is like waterblog.csdn.net/yanboberNo reprint without permission, please respect the author’s work.Contact me in private】