How to Create library module for Android applications – Best and easy 5 min tutorial

What are Libraries for Android applications?

The Android Support Library is a set of code libraries — resources that can be used to build features and/or functions into an app — that provide things like features or widgets that would normally require an actual Android framework API to include in an app. Android framework APIs are the core features available to developers provided by a specific version of Android. For example, Android 7.0 APIs enabled multi-window support for every app on every device. Support Libraries can provide similar features independently of the operating system version. In this tutorial we would learn to create library module for Android.

There are generally two types of support library packages. One set enables features of new versions of Android on devices running an older version and the other provides standalone features for all versions of Android. Because these aren’t part of Android proper, they can be improved and updated without waiting for a major Android platform release.

In addition to JAR files, the Android uses a binary distribution format called Android ARchive(AAR). The .aar bundle is the binary distribution of an Android Library Project.

An AAR is similar to a JAR file, but it can contain resources as well as compiled byte-code. A AAR file can be included in the build process of an Android application similar to a JAR file.

It is possible to create libraries modules which can be used as dependencies in Android projects. These modules allow you to store source code and Android resources which can be shared between several other Android projects.

To use a Java library (JAR file) inside your Android project, you can simple copy the JAR file into the folder called libs in your application. *.jar files in this folder are included into the compile classpath via the default build.gradle file.

Custom Android library modules

2.1. Using custom library modules

An Android library module can contain Java classes, Android components and resources. Only assets are not supported.

The code and resources of the library project are compiled and packaged together with the application.

Therefore a library module can be considered to be a compile-time artifact.

2.2. Creating custom Android library modules

Using library projects helps you to structure your application code. To create a new library module in Android Studio, select File  New Module and select Android Library.

How to create an Android library module for Android

Note that our library project will contain the data model and a method to get the number of instances. The library provides access to (fake) RSS data. An RSS document is an XML file which can be used to publish blog entries and news.

4.1. Create library module

For Android Studio each library is a module. To create a new library module in Android Studio, select File  New Module and select Android Library.

Create library module in Android
Creating new module

Use com.example.android.rssfeedlibrary as module name and Rssfeed Library as library name.

Setting the library property
Selecting Library Name and Package name

If prompted for a template select that no activity should be created. As a result Android Studio shows another module.

Setting the library property
Side bar

4.2. Remove generated dependency from build.gradle of the library project

Open the build.gradle of the library project. Delete the dependencies closure, your library does not need any dependency and the generated dependency can cause problems for the build.

Ensure you remove dependencies from the correct library project and not from your app.

4.3. Create the model class

Create an RssItem class which can store data of an RSS entry.

Generate the getters and setter, the constructor and a toString() method. The result should look like the following class:

package com.example.android.rssfeedlibrary;

public class RssItem {
    private String pubDate;
    private String description;
    private String link;
    private String title;

    public RssItem() {
    }

    public RssItem(String title, String link) {
        this.title = title;
        this.link = link;
    }
    public String getPubDate() {
        return pubDate;
    }

    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "RssItem [title=" + title + "]";
    }

}

4.4. Create instances

Create a new class called RssFeedProvider with a static method to return a list of RssItem objects. This method does currently only return test data.

package com.example.android.rssfeedlibrary;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RssFeedProvider {
    public static List<RssItem> parse(String rssFeed) {
        List<RssItem> list = new ArrayList<>();
        Random r = new Random();
        // random number of item but at least 5
        Integer number = r.nextInt(10) + 5;
        for (int i = 0; i < number; i++) {
            // create sample data
            String s = String.valueOf(r.nextInt(1000));
            RssItem item = new RssItem("Summary " + s, "Description " + s);
            list.add(item);
        }
        return list;
    }
}

4.5. Define dependency to the library project

To use the library add it as a dependency in your project select File  Project Structure. Select the app entry. Switch to the Dependencies tab and select Module dependencies via the + sign.

Define dependency in Android Studio - Selecting dependency
Project structure
Define dependency in Android Studio - Select module
choose model
Define dependency in Android Studio - Select module
Dependencies Window

4.6. Use library project to update detailed fragments

Update the updateDetail method in your MyListFragment class to use the RssFeedProvider provider. This is only test code.

public class MyListFragment extends Fragment {


    // triggers update of the details fragment
    public void updateDetail(String uri) {  // 
        List<RssItem> list = RssFeedProvider
                .parse(uri);
        String itemListAsString = list.toString();
        listener.onRssItemSelected(itemListAsString);
    }

4.7. Validate implementation

Start your application and ensure that the toString value of the list of RssItems is displayed in the DetailFragment.

The list is currently generated randomly every time you press the button.

5. Exercise: Deploy a library project

Create a new library project called recyclerbaseadapter with the same top level package. Add the following to its build.gradle file.

apply plugin: 'maven'

group = 'com.vogella.libraries'
version = '1.0'

uploadArchives {
    repositories {
        mavenLocal()
    }
}

Create or move a MyBaseAdapter class in this library.

Deploy it by running the gradle uploadArchives task.

You can now define a dependency to this library, by adding mavenLocal() and using:

compile 'com.vogella.libraries:recyclerbaseadapter:1.0`

Bonus : Development considerations for library modules

Once you have added references to library modules to your Android app module, you can set their relative priority. At build time, the libraries are merged with the app one at a time, starting from the lowest priority to the highest.

  • Resource merge conflictsThe build tools merge resources from a library module with those of a dependent app module. If a given resource ID is defined in both modules, the resource from the app is used.If conflicts occur between multiple AAR libraries, then the resource from the library listed first in the dependencies list (toward the top of the dependencies block) is used.To avoid resource conflicts for common resource IDs, consider using a prefix or other consistent naming scheme that is unique to the module (or is unique across all project modules).
  • In multi-module builds, JAR dependencies are treated as transitive dependenciesWhen you add a JAR dependency to a library project that outputs an AAR, the JAR is processed by the library module and packaged with its AAR.However, if your project includes a library module that is consumed by an app module, the app module treats the library’s local JAR dependency as a transitive dependency. In this case, the local JAR is processed by the app module that consumes it, and not by the library module. This is to speed up incremental builds that are caused by changes to a library’s code.Any Java resource conflicts caused by local JAR dependencies must be resolved in the app module that consumes the library.
  • A library module can depend on an external JAR libraryYou can develop a library module that depends on an external library. (for example, the Maps external library). In this case, the dependent app must build against a target that includes the external library (for example, the Google APIs Add-On). Note also that both the library module and the dependent app must declare the external library in their manifest files, in a <uses-library> element.
  • The app module’s minSdkVersion must be equal to or greater than the version defined by the libraryA library is compiled as part of the dependent app module, so the APIs used in the library module must be compatible with the platform version that the app module supports.
  • Each library module creates its own R classWhen you build the dependent app modules, library modules are compiled into an AAR file then added to the app module. Therefore, each library has its own R class, named according to the library’s package name. The R class generated from main module and the library module is created in all the packages that are needed including the main module’s package and the libraries’ packages.
  • A library module may include its own ProGuard configuration fileIf you have a library project that you use to build and publish an AAR, you can add a ProGuard configuration file to your library’s build configuration and the Android Gradle plugin applies the ProGuard rules that you have specified. The build tools embed this file within the generated AAR file for the library module. When you add the library to an app module, the library’s ProGuard file gets appended to the ProGuard configuration file (proguard.txt) of the app module.By embedding a ProGuard file in your library module, you ensure that app modules that depend on your library do not have to manually update their ProGuard files to use your library. When the Android Studio build system builds your app, it uses the directives from both the app module and the library. So, there’s no need to run a code shrinker on the library in a separate step.

Anatomy of an AAR file

The file extension for an AAR file is .aar, and the Maven artifact type should be aar as well. The file itself is a zip file containing the following mandatory entries:

  • /AndroidManifest.xml
  • /classes.jar
  • /res/
  • /R.txt
  • /public.txt

Additionally, an AAR file may include 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 ABIs)
  • /proguard.txt
  • /lint.jar
  • /api.jar
Dhaval

Dhaval

Dhaval is a tech geek who loves developing software, games and writing technical posts. In his free time, he loves to read novels.

We Recommend