How to create an Android Library?

 

How to create an Android library?

An Android library is structurally the same as an Android app module. It includes everything needed to build an app, including source code, resource files, and an Android manifest.

However, instead of compiling into an APK that runs on a device, an Android library compiles into an Android Archive (AAR) file that you can use as a dependency for an Android app module. Unlike JAR files, AAR files offer the following functionality for Android apps:

       AAR files can contain Android resources and a manifest file, which lets you bundle in shared resources like layouts and drawables in addition to Kotlin or Java classes and methods.

       AAR files can contain C/C++ libraries for use by the app module’s C/C++ code.

A library module is useful in the following situations:

       When building multiple apps that use some of the same components, such as activities, services, or UI layouts

       When building an app that exists in multiple APK variations, such as a free and paid version, that share core components

In either case, move the files you want to reuse into a library module and then add the library as a dependency for each app module.

Create a library module in project

To create a new library module in your project, proceed as follows:

1.   Click File > New > New Module.

2.   In the Create New Module dialog that appears, click Android Library, then click Next.

3.   Give your library a name and select a minimum SDK version for the code in the library, then click Finish

Once the Gradle project sync completes, the library module appears in the Project pane. If you don’t see the new module folder, make sure the pane is displaying the Android view.

 

Convert an app module to a library module

If you have an existing app module with code you want to reuse, you can turn it into a library module as follows:

1.   Open the module-level build.gradlefile

2.   Delete the line for the applicationId. Only an Android app module can define this.

3.   Find the `plugins` block at the top of the file that looks like this:

 

4.   Change it to the following:

 

 

5.   Save the file and click File > Sync Project with Gradle Files.

The structure of the module remains the same, but it now operates as an Android library. The build creates an AAR file instead of an APK.

When you want to build the AAR file, select the library module in the Project window and click Build > Build APK.

Import a library module to project

Click File > New > Import Module.

Add AAR or JAR file to project

1.   Add file to folder libs

 

2.   Add a path to the dependency in you app build.gradlefile

 

3.   Sync now