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 identical to the Android application module. What the application module can contain is allowed in the library, including code files, resource files, and manifest files.

The application module compiles an APK file that can be run directly on the device, but the library module is compiled with an Android archive file, or AAR. AAR files cannot be run directly on the device like an apk file, and we generally use it as a dependency on Android apps.

Plain jar files can contain only code files and manifest files, and arr files may contain not only code files, but also Android resource files and manifest files. This allows us to share resource files with Java code files like layout files, picture files, and so on. It can be said that the arr file is really a "JAR" package that is specifically owned by Android.

Library modules are useful in the following situations:

    • Create multiple apps that need to use multiple identical components, like activity, service, or UI layouts.
    • Create an app that may need to be compiled into multiple apk versions as needed, such as free and paid editions, and two versions need to use 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 as a dependency.

Creating a library Module

To create a new library module in your project, you can follow these steps:

    1. Click File > New > New Module.
    2. In the Create New Module window, select the Android Library and click Next (Next).
      There is also an option in this window to create a Java Library,java Library is the traditional jar file that we know. Jar files are useful in many projects, especially when you want to share code with other projects. However, the jar file does not allow the inclusion of 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.

As soon as the Gradle synchronization is complete, the Library module will appear in the project panel on the left.

Application module to library module

If you have an existing application module 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 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.

Adding libraries as dependencies for your app

In order to use the library module in the application module, you need to do the following:

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

    • Add the compiled arr (or jar) file:
      1. Click File > New Module.
      2. In the Create New Module window, click Import. jar/. AAR package and click Next.
      3. Enter the path where arr or jar files are located and click Finish. It is created as follows:

    • 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. It is created as follows:


The two ways to lead the library are different. If you are introducing a library module 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 that the library is listed in the Settings.gradle file, as shown below, where 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 on the application, as shown in the following fragment:

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 can then read any code and resource files that belong to the library module in the application module.

Another way to use local AAR files

In fact, we also have a way to introduce local AAR files, first in the project to establish an AAR directory, specifically for the AAR file, and then add the following configuration in the application's Build.gradle:

repositories {    flatDir {        ‘../aar‘   // aar目录    }}

Then copy the AAR file into the project/aar directory 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. The way it is now is a bit like the introduction of a jar package.

Attention:
Depending on the above conditions, if you configure Flatdir under the Allprojects.repositories block in Project's Gradle file, you find that the AAR file is not recognized by the app project. By law, no matter where the AAR files are placed, the configuration of Flatdir in the app's Gradle can be recognized. However, if the Flatdir is configured in Project Gradle, the AAR files can only be identified by placing them in the app's module.

Generating AAR files

We can generate AAR files by clicking Build > Make Project and the AAR file will be generated under project-name/module-name/build/outputs/aar/. In general, there will be two AAR files, a debug version, and a release version.

When we get the post-AAR file, we can publish it, and other small partners can use the above method to introduce the AAR file 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 contain one or more of the following optional entries:

    • /assets/
    • /libs/name.jar
    • /jni/abi_name/name.so (where 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, which means that the application module is allowed direct access. But if you want the resources in the library to be used internally only and not to be exposed externally, you should use this automatic private identity mechanism by declaring one or more exposed resources. Resources include all files in your project's res/directory, examples, layouts, and so on.

First, create a new Public.xml file under the res/values/of the library (if it does not exist), and then define the exposed resource name in Public.xml, the following sample code creates two names Lib_main_layout and Mylib_, respectively Public layout Resources and string resources for public_string:

<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 accessed directly by external dependencies. Resources that are not defined in them are implicitly private, and external dependencies cannot be legitimately accessed. Where name is the resource name, type is the resource type: string, Layout, drawable, Dimen, and so on.

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

When externally relying on the use of library private resources, you can not be prompted by the way of R point, which is also a means of not exposing private resources. If you force the resource to be used, the compiler warns you:

As can be seen from the above, lib_main_layout and mylib_public_string resources can be used directly, but not defined as private resources, external dependencies when used, the compiler will issue a warning message.

But here's a point to note that the use of private resources do not have any errors, the application module can use these private resources, the reason for providing this mechanism is to tell you that the library module does not want to expose these resources to you, perhaps these resources have special purpose and so on. If you really want to use a private resource, and you don't want the compiler to issue a warning like this, you can copy the private resource into 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 that is used to the library. Private resources are not within the scope of code completion and Theme Editor, and if you try to reference a private resource, Lint displays a warning.

Library Development Considerations

When you add a library module reference to your Android application module, the Library module merges 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. If the same resource ID is defined in two modules, then the resource of the application module is used by default.

    2. If there is a conflict 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 for common resource IDs, use prefixes that are unique in the module (or in all project modules) or other consistent naming schemes.

Let's take an example to show that point 1, opinion 2 interested students can verify themselves. First, the following string resources are defined 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 the following string resource:

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

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 of the Mytesttwo application and recompile, and you can see that two r files are generated in the application module:

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

We compare the contents of the 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 for the Mylibraryone library contains only its own resources, and all the resource values have changed. and the resource IDs in the library are also incorporated into the application's R file. A feature can be seen from the two files above:

The library's R file and the application's R file can access the library's resources, but the application resources cannot be accessed with the library's R file.

Now that the resources of the library and the resources of the application are now being merged, which is used when we use 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, if the resource name of the library and the application conflict, regardless of which R file is used, it uses the app's resources by default.

You may still have questions, if I use the Test_one resource in the library, is it the resource of the library or the application? The answer is an applied resource, because the library's R file resource ID values have changed since the library was merged into the app. When we use the R file to access the resource, we are going to access the changed R file, so if there is a resource conflict, the application resource will be the default. So here I can also draw another conclusion:

When libraries and application module resources conflict, the resource is applied by default, regardless of whether it is used in the app or in the library. The premise is that the application module has dependencies on the library module.

So to avoid resource conflicts with common resource IDs, use prefixes that are unique in the module (or in all project modules) or other consistent naming schemes. For example, if the library name is Pulltorefresh, then the resource name under the library can be prefixed with PTR.

About R files:

The R file (R.java) is automatically generated by the Android Resource Packaging tool AAPT (Android Asset Packaging tool) and contains the IDs of all the resources in the Res directory. Whenever a new resource is created, the ID of the resource is automatically added to the R file. We can use that ID in our code to perform any action on that resource. Note that if we delete the R file manually, the compiler will create it automatically.

The R file is a Java file because it is created automatically, so Android Studio will hide it in App/build/generated/source/r/debug

Resource conflicts and private resource issues

When a private resource exists in the Library module, the compiler warns if the Application module resource name and the private resource name conflict:

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

Although we use this resource with the application module resources, but the library has already marked Test_one as a private resource, in order to normalize, I can take the following measures:

    1. Replace the different resource names in the application module, not the same as the resource names in the library.
    2. If you really want to use a resource with the same name, 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>

This method does not cancel the private resource's status, except that the warning in the resource file is canceled.

Asserts merge conflicts

When the application depends on the library, the app's assert directory is merged with the library's asserts directory, and if the same path file is applied, the application module will prevail. For example, there are asserts/ha.json files in the application module, and there are asserts/ha.json files under the Library module, because the two paths are the same, and only the application module Asserts/ha.json is retained in the APK after merging. If the Library module's Ha.json file is stored in the Assert/json directory, then when merging, two JSON files exist because they have different paths, one is Asserts/ha.json and the other 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/directory), but after my testing, in the application module can freely use the library's assets resources without any problems.

About the asserts directory

Android resource files can be broadly divided into two types:

The first is the res directory stored in a compiled resource file: This resource file system will automatically generate the ID of the resource file in R.java, so access to this resource file is relatively simple, through the r.xxx.id can be;

The second is a native resource file stored under the assets directory:
Because the system does not compile the resource files under assets , we cannot access them in r.xxx.id way. Can I access them through the absolute path of the resource? Because APK installation will be placed in the/data/app/**.apk directory, in the form of APK, asset/res and is bound to the APK, and will not be extracted into the/data/data/yourapp directory down, 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 application's original resource file; This class provides a low-level API that allows you to open and read the raw resource files that are bound together with the application as a simple byte stream.

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

Libraries are compiled as part of the relevant application module, so the APIs used in the Library module must be compatible with the platform versions 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 added 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 module and library module are created in all required packages, including packages and libraries for the main module.

The library module may contain its own Proguard configuration file

You can enable code compression on your own library by adding the Proguard configuration file to the library that contains 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 app 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 the application module that relies on the library does not have to manually update its Proguard file to use the library. When Proguard is running on an Android application module, it uses instructions from both the application module and the library, so you should not run Proguard on the library.

To specify a profile name for 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 the Publishnondefault to true in the Build.gradle file of the library. For example, the following code snippet in your app's Build.gradle file will make the app use the library's debug build type when the application module is built in debug mode, and use the library's publishing build type when the application module is built in release mode:

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

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

android {    ...    true}

Note, however, that setting up Publishnondefault increases 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 therefore should not contain these rules. For example, your library's Proguard file can specify code that needs to be persisted during compression of the application module.

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

Reference documents

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.