Everything you need to know about creating an Android library

Source: Internet
Author: User

Everything you need to know about creating an Android library

The Android library is structurally similar to the Android application module. What the application module can include. All agree to exist in the library, including code files, resource files, and manifest files.

After the application module compiles an APK file that can be executed directly on the device, the library module is compiled with an Android archive file, or AAR.

AAR files cannot be executed directly on the device like an apk file, and we generally use it as a dependency on Android apps.

Plain jar files can only include code files and manifest files, and arr files can include not only code files. It can also include Android resource files and manifest files. Such We are able to share resource files with Java code files like layout files, picture files, and so on. The arr file is a "JAR" package that really belongs to Android.

Library modules are useful in the following situations:

    • Create multiple apps. These apps need to use several of the same components. such as activity, service, or UI layout.
    • Create an app. The app may need to be compiled into multiple APK version numbers, such as the free and paid editions, and two version numbers need to be used for the same components.

In either case, you just need to put the files you want to reuse in the library module, and then add the library to each application module in the form of a dependency.

Creating a library Module

In your project, create a new library module. You can follow steps such as the following:

    1. Click File > New > New Module.
    2. In the form of the Create New module. Select Android Library. and click Next (Next).
      There is also an option in the form for creating a Java Library,java Library is the traditional jar file that we know. Jar files are very useful in very many projects, especially when you want to share code with other projects. However, the jar file does not agree to include Android resource files and manifest files, and resource files are very helpful for code reuse in Android projects. So this article mainly introduces the Android library.
    3. Name your library and select the Minimum SDK version number, then click Finish to complete the creation.

Just to gradle the library module will appear in the project panel on the left after the synchronization is complete.

Application module to library module

Suppose you have an application module that already exists. and want to reuse all of its code. You can turn it into a library module:

1. Open the Build.gradle file that belongs to the application module, at the top, you can see such as the following display:

‘com.android.application‘

2. Change the plugin of the application to the library:

‘com.android.library‘

3. Click Sync Project with Gradle Files.

With this in the process, the structure of the entire module will not be changed, but the module has become a library module, which generates an AAR file and is no longer an apk file.

Add storage as a dependency of the application

In order to use the library module in the application module. You need to do the following, for example:

1. There are two ways to add a library to a project (assuming you are a library module created in the same project, the module already exists and you can skip this step)

    • Add the compiled arr (or jar) file:
      1. Click File > New Module.
      2. In the form of the Create New module, click Import. jar/. AAR package and click Next.
      3. Enter the path where arr or jar files are located. and click Finish. After creation, for example, the following are seen:

    • Import the external library module into the project:
      1. Click File > New > Import Module.
      2. Enter the path where the library module is located and click Finish. After creation, for example, the following are seen:


The two ways to lead the library are different. Assuming that the library module is introduced directly, you can edit the library's code.

However, if you import an AAR file, you cannot edit it, just like a jar file.

2. When the library module or AAR file is introduced to the project. Make sure the library is listed in the Settings.gradle file, as seen below. Among the mylibrary is the name of the library:

‘:app‘‘:mylibrary‘

3. Open the Build.gralde file under the Application module and add a new line to the dependencies block to make it a dependency of the application. For example, the following fragment is seen:

dependencies {    compile project(":mylibrary")}

4. Click Sync Project with Gradle Files.

Once the above information is configured, the library module named MyLibrary becomes a dependency of the application.

You will then be able to read the code and resource files in the application module, regardless of what is part of the library module.

There is also a way to use local AAR files

In fact, we also have a way to introduce local AAR files. First create an AAR folder under the project, specifically for the AAR file, and then add the following configuration to the application's Build.gradle, for example:

repositories {    flatDir {        ‘../aar‘   // aar文件夹    }}

Then copy the AAR file into the Project/aar folder and add the AAR reference to the dependencies of the application module:

‘mylibrary-debug‘‘aar‘)

With the above configuration, the AAR is introduced here. This approach is somewhat different from the introduction described above by encapsulating the imported AAR file into a separate module and then introducing it in the compile project way. And now this is a bit like the way a jar is introduced.

Attention:
Based on the above conditions, it is assumed that the FLATDIR is configured in Project's Gradle file under the Allprojects.repositories block, and the AAR file is not recognized by the app project. Through the law found, regardless of where the AAR files, only in the app's gradle configuration Flatdir can be recognized. However, assuming that Flatdir is configured in Project Gradle, it can only be identified by placing the Aar file in the app's module.

Generating AAR files

We are able to generate AAR files by clicking Build > Make Project and the AAR file will be generated under project-name/module-name/build/outputs/aar/. Under normal circumstances there will be two AAR files, a debug version number. A release version number.

When we get back AAR files. will be able to publish it out. Other small partners will be able to use the above method to introduce AAR files into the project.

AAR file gouging

AAR file extension. AAR, which is itself a zip file and must include the following:

    • /androidmanifest.xml
    • /classes.jar
    • /res/
    • /r.txt (converted from R.java)

In addition, the AAR file may include one or more of the following optional entries:

    • /assets/
    • /libs/name.jar
    • /jni/abi_name/name.so (Abi_name is one of the Android-supported ABI)
    • /proguard.txt
    • /lint.jar
Private Resources for libraries

By default, all resources in the library are exposed. In other words, you agree to use the module directly. But suppose you want the resources in the library to be used internally, rather than exposed to the outside. You should use such a self-active private identity mechanism by declaring one or more public resources. Resources include all files, images, layouts, and so on in your project's res/folder.

First, create a new Public.xml file under the res/values/of the library (assuming it does not exist), and then define the exposed resource name in Public.xml. The following demo sample code can create two public layout and string resources named Lib_main_layout and mylib_public_string, respectively:

<resources>    <public name="lib_main_layout" type="layout"/>    <public name="mylib_public_string" type="string"/></resources>

The two resources defined above represent a public state and can be directly interviewed by external dependencies. Resources that are not defined in them are implicitly private, and external dependencies cannot be legitimately interviewed.

The name is the resource name and type is the resource type: string, Layout, drawable, Dimen, and so on.

Note that if you want to make all the resources in the library private, you must define at least one attribute in Public.xml.

You cannot be prompted by R points when you externally rely on the use of library private resources. This is also a means of not exposing private resources. If you force the resource to be used, the compiler issues a warning:

Can be seen from above. Lib_main_layout and mylib_public_string resources can be used directly, but not defined as private resources, when external dependencies are used, the compiler issues a warning message.

However, it is important to note that the use of private resources does not occur regardless of error. The application module is able to use these private resources normally. The reason for providing such a mechanism is to tell you. Library modules do not want to expose these resources to you, perhaps these resources have special purposes and so on. Suppose you really want to use a private resource. And don't want the compiler to warn you, you can copy the private resources to your own application module.

The private property of the resource is not only protected from external use, but also allows you to rename or delete a private resource without affecting the application module used to that library. Private resources are not within the scope of the code's own initiative and Theme Editor, and if you try to reference a private resource, Lint will display a warning.

Library Development Considerations

Once the Library module reference is added to your Android application module, the Library module is merged with the application module in the order of precedence.

Resource merge conflicts
    1. The build tool merges the resources in the library module with the resources of the relevant application module.

      Assuming that the same resource ID is defined in two modules, the resource for the application module is used by default.

    2. Assuming a conflict occurs between multiple AAR libraries, the resource in the library that is listed first (at the top of the dependencies block) is used in the dependency list.

To avoid resource conflicts that often use resource IDs. Use a prefix or other consistent naming scheme that is unique in the module (or in all project modules).

Let's give a sample to prove the point 1. Views 2 Interested students can verify themselves.

A string resource such as the following is defined first in the Library module Mylibraryone:

<resources>    <string name="app_name">My Library</string>    <string name="test_one">My name is Library</string>    <string name="my_library">Library</string></resources>

Through the library's R file, the ID values for these three resource files are: app_name=0x7f020000, my_library=0x7f020001, test_one=0x7f020002

Then in the application module Mytesttwo This also defines a string resource such as the following:

<resources>    <string name="app_name">MyTestTwo</string>    <string name="test_one">My name is App</string></resources>

Please note that. The resource names App_name and Test_one are the same as the string resource names defined in the library.

We take the Mylibraryone library as a dependency on the Mytesttwo application and compile it again. We are able to send two r files generated by the application module today:

The first one is the R file after the library is merged, and the second one is to apply its own R file.

We control. Contents of two R files:
Mylibraryone:

 Public Final  class R {     Public Static Final  class string {         Public Static Final intApp_name =0x7f040000; Public Static Final intMy_library =0x7f040001; Public Static Final intTest_one =0x7f040002; }}

Mytesttwo:

 Public Final  class R {..... Public Static Final  class mipmap {         Public Static Final intIc_launcher=0x7f020000; } Public Static Final  class string {         Public Static Final intApp_name=0x7f040000; Public Static Final intmy_library=0x7f040001; Public Static Final intTest_one=0x7f040002; }}

The r file of the Mylibraryone library only includes its own resources, and all of the resource values have changed. Also, the resource IDs in the library are incorporated into the application's R file.

A feature can be seen from the two files above:

You can access the library's resources by using the library's R file and the application's R file. However, you cannot use the library's R file to access application resources.

Now that the resources of the library and the resources of the application are now merged. Which is the use of the Test_one string? We output the ID value directly under the application module to see:

LOG.D ("CRYC","APP:"+integer.tohexstring (Com.example.mytesttwo.r.string.test_one) +""); LOG.D ("CRYC","APP:"+getstring (Com.example.mytesttwo.r.string.test_one) +""); LOG.D ("CRYC","Library:"+integer.tohexstring (Com.example.mylibraryone.r.string.test_one) +""); LOG.D ("CRYC","Library:"+getstring (Com.example.mylibraryone.r.string.test_one)); LOG.D ("CRYC","Library:"+integer.tohexstring (com.example.mylibraryone.r.string.my_library)); LOG.D ("CRYC","Library:"+getstring (com.example.mylibraryone.r.string.my_library));

Output Result:

App:7f040002App:My name is AppLibrary:7f040002Library:My name is AppLibrary:7f040001Library:Library

As you can see, it is assumed that the resource name of the library and the application conflict, regardless of which R file is used. All that uses the app's resources by default.

You may still have questions. Suppose I use a test_one resource in a library, is it a resource used by a library or an application? The answer is the applied resource, since the library is merged into the app. The library's R file resource ID values have changed.

And we use the R file to access resources. is to get access to the changed R file, so assume that there are resource conflicts by default, whichever is the application resource. So here I can also conclude that there is one more conclusion:

When libraries and application module resources conflict, the resource is used either in the app or in the library. Are the primary application resources by default. The premise is that the application module has dependencies on the library module.

So in order to avoid resource conflicts that often use resource IDs. Use a prefix or other consistent naming scheme that is unique in the module (or in all project modules).

For example, the library name is Pulltorefresh. Then the resource name under the library can be prefixed with PTR.

About R files:

R file (R.java) is self-generated by the Android Resource Packaging tool AAPT (Android Asset Packaging tool), including the ID of all resources under the Res folder.

Whenever a new resource is created, the ID of the resource is added to the R file on its own initiative. We can use that ID in our code to do whatever it is about that resource. Note that suppose we manually delete the R file. The compiler will create it on its own initiative.

The R file is a Java file, and since it was created on its own initiative, Android Studio will hide it, with a detailed location in App/build/generated/source/r/debug

Resource conflicts and private resource issues

When a private resource exists in the library module, it is assumed that the Application module resource name and the private resource name conflict, and the compiler warns:

This warning is also emitted when we use the resource in the app:

Although we use this resource with the resources of the application module. However, the library has marked the Test_one as a private resource, in order to standardize. I can take measures such as the following:

    1. Replace the different resource names in the application module. Do not have the same name as the resource in the library.

    2. Suppose you really want to use a resource with the same name and use tools to mark the override state:
<resources xmlns:tools="http://schemas.android.com/tools">    <string name="app_name">MyTestTwo</string>    <string name="test_one" tools:override="true">My name is App</string></resources>

In this way, it is not possible to cancel the private resource, which is the state of the privately owned resources, but only cancels the warning in the resource file.

Asserts merge conflicts

When the app depends on the library, the app's Assert folder is merged with the library's asserts folder, assuming that the same path file is applied, whichever is the application module. For example, the application module exists Asserts/ha.json file, the Library module also has the Asserts/ha.json file, because of the same two paths. When the merge apk only retains the app module Asserts/ha.json. Assume that the Library module's Ha.json file is stored under the Assert/json folder. Then, when merging, two JSON files are present. Because they are not the same path. One is Asserts/ha.json and one is Asserts/json/ha.json.

Google official said: The tool does not support the use of the original resource files in the Library module (saved in the assets/folder), but after my test, in the application module can use arbitrary assets resources in the library no matter what.

About the asserts folder

Android resource files can be broadly divided into two types:

The first is a compiled resource file stored under the Res folder: Such a resource file system will proactively generate the ID of the resource file in R.java, so it is easier to access such resource files. Through the r.xxx.id can be;

The other is a native resource file stored under the Assets folder:
Because the system does not compile the resource files under assets when compiling . So we can't access them through the r.xxx.id way.

Can I visit them through the absolute path of the resource? Since the APK is installed, it will be placed under the/data/app/**.apk folder. In the form of an apk, asset/res and is bound to the APK, and will not be unpacked into the/data/data/yourapp folder. So we can't get the absolute path to the assets directly. Because they don't have it at all.

Fortunately the Android system provides us with a Assetmanager tool class. Viewing the official API, Assetmanager provides access to the original resource file for the application, which provides a low-level API. It agrees that you open and read the original resource file that is bound together with the application in the form of a simple byte stream.

The minsdkversion of the application module must be greater than or equal to the version number defined by the library

Libraries are compiled as part of the relevant application module, so. The API used in the Library module must be compatible with the platform version number supported by the application module.

Each library module will create its own R class

When you build the relevant application module, the Library module is first compiled into the AAR file. And then add it to the application module. Therefore, each library has its own R class and is named according to the library's package name.

The R classes generated from the main and library modules are created in all required packages, including packages and libraries for the main module.

The library module may include its own Proguard configuration file

You can enable code compression on your own library by joining the Proguard configuration file to a library that includes its proguard directives. The build tool embeds this file into the generated AAR file for the library module. When you add a library to an application module, the library's Proguard file is appended to the application module's proguard configuration file (proguard.txt).

By embedding the Proguard file in your library module. You can ensure that application modules that rely on this library can use the library without having to manually update their proguard files. When the Proguard is executed on the Android application module. It will use instructions from the application modules and libraries at the same time, so you should not just perform proguard on the library.

To specify the profile name of your library, add it to the Consumerproguardfiles method, which is within the defaultconfig block of the Build.gradle file for your library. For example, the following fragment sets Lib-proguard-rules.txt as the library's proguard configuration file:

android {    defaultConfig {        ‘lib-proguard-rules.txt‘    }    ...}

By default, the application module is built with the publication of the library, even when using the debug build type of the application module. To use different build types in the library, you must add the dependencies to the dependencies block of the app's Build.gradle file. and set Publishnondefault to true in the library's Build.gradle file. Like what. The following code snippet in your application's Build.gradle file will make the application use the library's debug build type when the application module is built in debug mode, and use the publication build type of the library when the application module is built in publish mode:

dependencies {    ‘:library‘‘debug‘)    ‘:library‘‘release‘)}

You must also include the following line of code within the Android block of your library's Build.gradle file. To present the non-advertised configuration of this library to the project that uses it:

android {    ...    true}

Just be careful. Setting Publishnondefault will add build time.
To ensure that your library's Proguard rules do not apply unexpected compression side effects to the application module, include only the appropriate rules to deactivate the Proguard feature that does not apply to this library.

The rules that attempt to assist the developer may conflict with existing code in the application module or its other libraries and should not be included. Like what. Your library's Proguard file can specify code that needs to be retained during compression of the application module.

Note: The Jack toolchain only supports partial compression and blur options for Proguard

Documentation for references

Https://developer.android.com/studio/projects/android-library.html#aar-contents
http://www.jianshu.com/p/59efa895589e
http://tikitoo.github.io/2016/05/26/android-studio-gradle-build-run-faster/
http://blog.csdn.net/z1074971432/article/details/38912747

Everything you need to know about creating an Android library

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.