Android application development compilation framework process and IDE and Gradle overview

Both Android's Dalvik and ART runtime environments can execute .dex files generated by the dx tool, which means that Dalvik and ART use the same Dalvik instruction set. Through [Related Information Query]((), we can know that the Dalvik instruction set uses 16-bit registers to save all method references in the project. The 16th power of 2 is 65536, which means that a dex file can only reference 65536 methods at most. So for both Dalvik and ART runtime environments, there is this limitation. I'll go!!! This is why we sometimes throw Android Dex method limitation exceptions when compiling projects (also introduced above, I don't understand Look back), which means that this exception is thrown at compile time because the project contains too many methods. Fortunately, Google officials are also aware of this defect, so they give a solution, as follows:

  • Use ProGuard to clear useless methods in the project, and use related scripts to clear methods in third-party libraries that are not used in the project;

  • Since the Dalvik runtime environment restricts an apk to contain only one classes.dex file, we can use the Multidex Support Library support package to support multiple .dex files in one apk, so that the limit of 65536 can be broken.

This error in the dx process is very classic, and generally occurs when a large number of third-party libraries are used, so you need to pay attention.

2-2-4 apkbuilder tool

The name of the apkbuilder tool is actually a bit outdated, because the apkbuilder tool has been removed in the newer version of the SDK, but the essence of the apkbuilder tool is actually ApkBuilderMain in /android-sdk-linux/tools/lib/sdklib.jar It is just an encapsulation, so even without this tool, we can implement encapsulation by ourselves, but the new compilation framework will automatically help us solve this process, and we do not need to deal with it manually. The essence of this process is actually similar to the nature of the compression tool, except that it packs and compresses related resources, dex files, etc. into an apk file with a specified compression method and depth.

2-2-5 keytool and jarsigner tool

The essence of signing the apk packaged and compressed by apkbuilder is to write specific tag information in a specific field of the application to indicate that the software has passed the review of the signer. The function of the signature is to identify the author of the application , detect whether the application of the Android open source project "ali1024.coding.net/public/P7/Android/git" has been changed, and detect whether it is the same application.

Generally, we can use the keytool tool to generate the signature private key, and then use the jarsigner tool to use the private key to sign the application. However, this process is very simple, so I won't repeat it here, just make up your own mind.

2-2-6 zipalign tool

The zipalign tool can optimize the packaged application. The optimized application can achieve maximum execution efficiency at runtime and occupy less RAM (Random Access Memory) memory. zipalign performs 4-byte alignment on the data in the apk file, 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 code by calling the mmap function after alignment. Fetching files, that is to say, the process can operate ordinary files in our apk like reading and writing memory, so when an aligned application is executed in the system, reading resources through shared memory IPC can get higher performance, if there is no alignment processing, then It is necessary to display methods such as dispatching read to manipulate data, which means that the running process will be slower and will consume more memory, resulting in performance degradation.

The use of the zipalign tool is no longer verbose here, because usually the compilation framework allows us to configure the script directly without executing the command manually.

2-2-7 ProGuard Tools

ProGuard is a tool for compressing, optimizing and obfuscating Java bytecode class files. It can delete useless classes, fields, methods, attributes and useless comments, etc., and optimize class bytecode files to the greatest extent. It can also rename already existing classes, fields, methods, and properties with short, nonsensical names. We usually use it to confuse the final project, and then slightly increase the difficulty of the project being decompiled. Of course, for the current technology, the difficulty of decompilation is no longer a problem. We still focus on its optimization of useless resources and concise replacement. Bar.

The use of ProGuard tools is no longer verbose here, because usually the compilation framework allows us to configure scripts directly without executing commands manually.

2-2-8 jobb tool

In fact, this tool does not belong to the normal process of compiling the framework, it is just an extension feature of Android. Since Android version 2.3, the system has added an OBB file system (permission access restriction isolation file system) and the StorageManager class to manage data security on external storage.

If you have installed the "Monument Valley" or "Mechanical City" game on your Android phone before, then you can have a good understanding of the jobb tool and OBB file system mentioned here. Do you still remember that after installing a game with a size of dozens of megabytes, you need to download a zip archive of more than 200 megabytes and put it in the Android/obb/[GamePackageName] directory of the file system to play the game normally. The reason for this is because our game project contains a lot of resources (pictures, videos, music, etc.), and the direct compilation into APK may be as high as hundreds of megabytes, and the system will have a limit on the size of the APK file when installing the APK , such a large APK file will definitely cause the Android system to fail to install the APK normally; I believe that you who are wise at this time will say that we will put these resources directly on the SD card and it will be over? Haha, have you ever thought about a question, if you put it directly on the SD card, wouldn’t the system’s music, video, pictures and other managers be able to directly index these things, which would be very bad (insert a sentence, you can also add These resources are saved without the suffix, so that these media libraries cannot be indexed. For example, the attachments of the Android system mail application are designed like this, which is really clever!). Fortunately, the OBB file of Android 2.3 can solve this series of problems very well.

In this case, the OBB file system must require that the stored files must conform to a certain format, and jobb is a tool to solve this problem. jobb allows us to generate encrypted or unencrypted OBB format expansion files. OBB files can be used as extended resource files for Android applications, which exist independently of APK files. Here is the documentation for the jobb tool:

write picture description here

The jobb tool will not be explained in depth here. Generally, this design may be considered in the development of large-resource applications such as games. It is not too late to make up for it when it is used.

2-3 Android application compilation Jack and Jill new toolchain


At this point, everyone already has a good understanding of the conventional application compilation framework, but the question is, do you also think that the current Android compilation and construction process is quite painful (compilation and construction are extremely slow), in fact, Google official seems to Also aware of this problem, they also gave some optimization explanations at the current stage at this year's Google IO conference. Among them, the most worth-trying and mentioning highlights are the two new compilers Jack and Jill (the current official claim is still Experimental The experimental compiler is not robust enough, it is still in the bug collection stage, currently does not support annotation processing, does not support Java 8, etc., so it is still cautious), the official said that these two compilers are designed to simplify the Android compilation process, to put it bluntly That is, try to speed up the compilation and build. Let's first look at the build process using the Jack and Jill compilers:

write picture description here

As you can see, Jack is a tool based on Java compiler and ProGuard, but the current version does not support some advanced features of ProGuard (such as removing logging code). Jill converts the Java library bytecode into an intermediate bytecode .jack file named jayce. Jack compiles the Java source code and jayce bytecode to generate optimized dex bytecode.

If you want to use Jack and Jill early, you need to ensure that your Build Tools version is 21.1.1 or higher. Configured in Gradle as follows:

android {

buildToolsRevision ‘21.1.2’

defaultConfig {

// Enable the experimental Jack build tools.

useJack = true

}

}

In a word, I'm still young now, so I have to wait and see what I can achieve. Let's see the future development trend. Anyway, I haven't used him much at the moment, I'm just trying it out experimentally.

[Artisan Ruoshui [http://blog.csdn.net/yanbober](() Reprinting without permission is strictly prohibited, please respect the author's labor results. [Contact me privately](()]

3 Android application IDE and compilation related features

=========================

The following introduces some efficient code writing features in the development process of using IDE, and also includes some compilation-related attention features, which will be described in detail below.

3-1 Android application jar package and aar package


When we compile our own library in Android Studio, two packages, jar and aar, will be generated at the same time. Their specific paths are 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 of them is as follows (in essence, they are all compressed packages):

| Package Type | Description |

| — | — |

|jar | Contains only class files, not resource files, for libraries written in pure Java. |

| aar | Contains all resources such as all classes and res, similar to UI libraries. |

In fact, the difference between them can be seen intuitively by decompressing them, and will not be described here.

3-2 Android Tools Attributes Compilation Instructions


There is also a useful tool attribute that needs to be known in the Android application compilation framework, that is, the tools namespace attribute, whose namespace URI is [http://schemas.android.com/tools]((), it can be said that this namespace It is specially designed for developers and is only valid in the design phase, not in the running phase.

3-2-1 The method of binding the tools namespace

<FrameLayout xmlns:android=“http://schemas.android.com/apk/res/android”

// bind namespace

xmlns:tools=“http://schemas.android.com/tools”

android:layout_width=“match_parent”

android:layout_height=“match_parent” >

The tools attribute can replace all Android attributes. It is only valid in the design phase and will not be brought into the final apk, so it is invalid at runtime. The attributes of the entire tools namespace are divided into two categories, one is Lint-related and the other is design-related. Below we list some useful properties related to tools.

3-2-2 tools:ignore

Tell Lint to ignore certain warnings in xml. Use as follows:

//Ignore Lint's warning for multi-language detection, multiple can be separated by commas

All

3-2-3 tools:targetApi

Used to specify the API level, the function is similar to the @TargetApi annotation in the Java file, the value is an integer or a meaning string. Use as follows:

3-2-4 tools:locale

By default, the strings in the res/values/strings.xml file will be spell-checked, and a warning will be given if the locale is not English. We can specify the locale by doing this and ignore the warning. as follows:

3-2-5 tools:context

"Android Study Notes Summary + Latest Mobile Architecture Video + Big Factory Android Interview Questions + Project Practical Source Code Lectures" The open source attribute is actually the associated Activity attribute. After adding this attribute to the xml, you can preview the xml file to know what theme to use to preview , and the Activity file and the xml file are associated at the same time, and the index can be jumped directly from the java file. as follows:

<android.support.v7.widget.GridLayout xmlns:android=“http://schemas.android.com/apk/res/android” xmlns:tools=“http://schemas.android.com/tools”

tools:context=".MainActivity" … >

3-2-6 tools:layout

This attribute is used in the fragment node of xml to tell the IDE how the fragment will look in preview mode during development. as follows:

3-2-7 tools:listitem / listheader / listfooter

Obviously you can guess the item and header used to specify the preview for ListView, AdapterView, GridView, ExpandableListView. as follows:

<ListView

android:id="@android:id/list"

android:layout_width=“match_parent”

android:layout_height=“match_parent”

tools:listitem="@android:layout/simple_list_item_2" />

3-2-8 tools:showIn

This property is set to the root node of an included layout and is available during preview. as follows:

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:tools=“http://schemas.android.com/tools”

android:text="@string/hello_world"

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

tools:showIn="@layout/activity_main" />

3-2-9 tools:menu

Used to tell the IDE to display the specified menu style in the current xml layout when previewing. In fact, if we specify the tools:context attribute, the IDE will intelligently look for the menu style preview in the onCreateOptionsMenu method in the specified Activity file. Of course, we can override the menu preview in Activity through this property. as follows:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:tools=“http://schemas.android.com/tools”

android:orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

tools:menu=“menu1,menu2” />

3-2-10 tools:actionBarNavMode

Specifies the preview mode of the actionbar. Optional values ​​are "standard", "list", "tabs". as follows:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”

xmlns:tools=“http://schemas.android.com/tools”

android:orientation=“vertical”

android:layout_width=“match_parent”

android:layout_height=“match_parent”

tools:actionBarNavMode=“tabs” />

3-2-11 Designtime design-time properties

The tools attribute can replace all Android attributes. It is only valid in the design phase and will not be brought into the final apk, so it is invalid at runtime. For example, when we most commonly write a TextView, we don't want to give him the initial text content in xml, and we want to preview it. At this time, we can use the tools attribute instead. as follows:

<TextView

tools:text=“Name:”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

tools:visibility=“invisible” />

It can be seen that the tools namespace attributes can speed up the flexibility and predictability of our development. At the same time, these attributes are ignored in the compilation framework and do not bring them into the final product apk. We can choose whether to use these in development as appropriate. Attributes.

3-3 Android Annotations annotation description


A new annotation package has been added to the 19.1 version of the Android Support Library. This package is used to annotate the code to facilitate the capture of problems and bugs in the program. The code inside this package has already used the annotation. In version 22.2, Added 13 new annotations. These annotations can facilitate our code development and deployment specifications and bug checking. The specific usage will be explained one by one below.

3-3-1 Annotation Library Dependency Reference

The annotations annotation package is not automatically included by default, but it is automatically included if the appcompat package is used, because the annotations are used in the appcompat package.

The annotation package is introduced into the Gradle file of the Android project as follows:

dependencies {

compile ‘com.android.support:support-annotations:22.2.0’

}

If you don't want to use the annotation package in the Android project, you can write it as follows (url is the annotation package path of the local android sdk):

repositories {

jcenter ()

maven { url ‘/extras/android/m2repository’ }

}

3-3-2 Execute annotation

When we use Android Studio and IntelliJ, if we pass the wrong type parameter to the annotated method, the IDE will mark the error in real time. If you are using Gradle version 1.3.0 or later and Android M Preview Tools or above are installed, you can call gradle's lint task through the command line to check (nullness annotation will be ignored).

3-3-3 Null empty type judgment annotation

The @Nullable annotation is used to mark that a given parameter or return value can be null.

The @NonNull annotation is used to mark that the given parameter or return value cannot be null.

Suppose a local variable value is null, and it is passed as a parameter to a method, and the parameter of the method is annotated with @NonNull, then AS will alert that there is 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) {

3-3-4 Resource Type Annotation

Android resource values ​​are usually associated with the integer id mapped by the R file, that is to say, getting a resource parameter of layout type can easily be mistakenly passed a resource parameter of another type, because they are all integer resource ids. , it is difficult for the compiler to distinguish. To solve this problem you can use resource type annotations because annotations provide type checking. For example, the following is an integer parameter annotated with @LayoutRes but a resource parameter of string type is passed, and the IDE will give an error message:

The wrong parameter was passed when calling the setContentView method:

write picture description here

The resource annotation implementation method of setContentView:

write picture description here

There are actually many different resource type annotations such as @AnimatorRes, @AnimRes, @AnyRes, @ArrayRes, @AttrRes, @BoolRes, @ColorRes, @DimenRes, @DrawableRes, @FractionRes, @IdRes, @IntegerRes, @InterpolatorRes, @LayoutRes, @MenuRes, @PluralsRes, @RawRes, @StringRes, @StyleableRes, @StyleRes, @XmlRes, etc. Generally, the corresponding resource type annotation for a foo type resource is @FooRes. In addition to this, there is a special resource type annotation called @AnyRes, which is used to annotate a resource of an unknown special type, and must be a resource type. For example, when using Resources.getResourceName(@AnyRes int resId), we can use getResources().getResourceName(R.drawable.icon) and getResources().getResourceName(R.string.app_name), etc., but But it cannot be used by getResources().getResourceName(42).

3-3-5 IntDef/StringDef Type Annotation

This type of annotation is based on Intellij's magic number checking mechanism, because in Android development, we often use integer constants instead of enumeration types for performance reasons. For example, an example in 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);

The non-annotated part above is the original code and API. We created a new annotation NavigationMode through @interface, marked its possible values ​​with @IntDef, and added @Retention(RetentionPolicy.SOURCE) to tell the compiler this new definition The annotation does not need to be recorded in the generated .class file; after using this annotation, if the parameter we return or pass is not in the specified constant value, the IDE will give an obvious error prompt.

We can also specify an integer constant as a marked type, because then multiple integer constants can be passed at the same time through operators such as |, &, etc. The following 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 {}

@StringDef and @IntDef are basically the same, the difference is that it is for strings. [For more information about type annotations, click me to get](().

3-3-6 Thread annotation @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 use the following 4 annotations to annotate them:

  • @UiThread

  • @MainThread

  • @WorkerThread

  • @BinderThread

If all methods in a class have the same threading requirements then the class itself can be annotated.

An example of the use of thread annotations is AsyncTask, as follows:

@WorkerThread

protected abstract Result doInBackground(Params… params);

At last

Since there are too many questions and the workload of arranging answers is too much, I am limited to providing knowledge points. I have organized many detailed questions and reference answers into PDF files.


public @interface DisplayOptions {}

@StringDef and @IntDef are basically the same, the difference is that it is for strings. [For more information about type annotations, click me to get](().

3-3-6 Thread annotation @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 use the following 4 annotations to annotate them:

  • @UiThread

  • @MainThread

  • @WorkerThread

  • @BinderThread

If all methods in a class have the same threading requirements then the class itself can be annotated.

An example of the use of thread annotations is AsyncTask, as follows:

@WorkerThread

protected abstract Result doInBackground(Params… params);

At last

Since there are too many questions and the workload of arranging answers is too much, I am limited to providing knowledge points. I have organized many detailed questions and reference answers into PDF files.

[External link image dumping...(img-7k2bscTi-1650347797890)]

[External link image dumping...(img-qjrI1Zlb-1650347797891)]

[External link pictures are being transferred...(img-5yWE07kZ-1650347797892)]

Guess you like

Origin blog.csdn.net/m0_54883970/article/details/124272112