Android Phones

How to Create library module for Android applications

Dhaval
How to Create library module for Android applications

Want to make your Android coding more efficient and reusable?

We’ve got you covered! This guide will show you how to build a library module for Android apps.

No matter if you’re new to coding or a seasoned pro, you’ll learn what modules are how to create them, and how to add them to your Android Studio projects. We’ll break it down step by step, so you can start using modules to improve your development process.

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.

  1. Understanding Modules in Android Studio

In Android Studio, modules are defined in the settings.gradle file at the root of your project. When you create a new module, Android Studio automatically adds it to this file:

gradle Copy code// settings.gradle
include ':app', ':mylibrary'
  1. Android App Module vs. Android Library Module

Let’s look at the build.gradle files for both types of modules to understand their differences:

App Module (app/build.gradle):

gradle Copy codeapply plugin: 'com.android.application'

android {
    compileSdkVersion 33
    defaultConfig {
        applicationId "com.example.myapp"
        minSdkVersion 21
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"
    }
    // ...
}

dependencies {
    // ...
}

Library Module (mylibrary/build.gradle):

gradle Copy codeapply plugin: 'com.android.library'

android {
    compileSdkVersion 33
    defaultConfig {
        minSdkVersion 21
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"
        
        // Note: No applicationId for library modules
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles "consumer-rules.pro"
    }
    // ...
}

dependencies {
    // ...
}
  1. Step-by-Step Guide: Creating a Library Module

After creating the library module as described earlier, let’s add some functionality:

java Copy code// mylibrary/src/main/java/com/example/mylibrary/MathUtils.java
package com.example.mylibrary;

public class MathUtils {
    public static int add(int a, int b) {
        return a + b;
    }
    
    public static int subtract(int a, int b) {
        return a - b;
    }
}
  1. How to Add a Module to an Android Studio Project

In your app’s build.gradle file:

gradle Copy code// app/build.gradle
dependencies {
implementation project(':mylibrary')
// other dependencies...
}
  1. Using Your Android Library Module

Now, let’s use the library in our main app:

java Copy code// app/src/main/java/com/example/myapp/MainActivity.java
package com.example.myapp;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.example.mylibrary.MathUtils;

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TextView resultTextView = findViewById(R.id.resultTextView);

int sum = MathUtils.add(5, 3);
int difference = MathUtils.subtract(10, 4);

String result = "Sum: " + sum + ", Difference: " + difference;
resultTextView.setText(result);
}
}
  1. Advanced Library Module Features

Let’s explore some advanced features you can implement in your library module:

a. Custom Views:

java Copy code// mylibrary/src/main/java/com/example/mylibrary/CustomButton.java
package com.example.mylibrary;

import android.content.Context;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatButton;

public class CustomButton extends AppCompatButton {
    public CustomButton(Context context) {
        super(context);
        init();
    }

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setAllCaps(false);
        setPadding(20, 10, 20, 10);
    }
}

b. Resource Files: You can include resource files in your library module. For example, let’s add a color resource:

xml Copy code<!-- mylibrary/src/main/res/values/colors.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="library_primary_color">#3F51B5</color>
</resources>

c. Interfaces for Callback:

java Copy code// mylibrary/src/main/java/com/example/mylibrary/DataFetchCallback.java
package com.example.mylibrary;

public interface DataFetchCallback {
    void onSuccess(String data);
    void onError(String errorMessage);
}

// mylibrary/src/main/java/com/example/mylibrary/DataFetcher.java
package com.example.mylibrary;

import android.os.Handler;
import android.os.Looper;

public class DataFetcher {
    public static void fetchData(final DataFetchCallback callback) {
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                // Simulating network call
                callback.onSuccess("Data fetched successfully");
            }
        }, 2000);
    }
}

Using these advanced features in your main app:

java Copy code// app/src/main/java/com/example/myapp/MainActivity.java
package com.example.myapp;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.example.mylibrary.CustomButton;
import com.example.mylibrary.DataFetcher;
import com.example.mylibrary.DataFetchCallback;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CustomButton customButton = findViewById(R.id.customButton);
        customButton.setBackgroundColor(getResources().getColor(com.example.mylibrary.R.color.library_primary_color));
        
        customButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DataFetcher.fetchData(new DataFetchCallback() {
                    @Override
                    public void onSuccess(String data) {
                        Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(String errorMessage) {
                        Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}
  1. Publishing Your Library

To make your library available to other developers, you can publish it to a repository like JitPack. Here’s how:

a. Create a github.properties file in your project root:

properties Copy codegpr.usr=YOUR_GITHUB_USERNAME
gpr.key=YOUR_GITHUB_PERSONAL_ACCESS_TOKEN

b. Update your project-level build.gradle:

gradle Copy code// build.gradle (Project level)
buildscript {
    repositories {
        // ...
        maven {
            url "https://jitpack.io"
        }
    }
}

c. Update your library module’s build.gradle:

gradle Copy code// mylibrary/build.gradle
apply plugin: 'com.android.library'
apply plugin: 'maven-publish'

android {
    // ...
}

afterEvaluate {
    publishing {
        publications {
            release(MavenPublication) {
                from components.release
                groupId = 'com.github.yourusername'
                artifactId = 'mylibrary'
                version = '1.0.0'
            }
        }
    }
}

d. Push your code to GitHub and create a release.

e. Other developers can now use your library by adding the following to their project-level build.gradle:

gradle Copy codeallprojects {
    repositories {
        // ...
        maven { url 'https://jitpack.io' }
    }
}

And in their app-level build.gradle:

gradle Copy codedependencies {
    implementation 'com.github.yourusername:mylibrary:1.0.0'
}

By following these steps and exploring the code examples, developers can create powerful, reusable components for their Android projects. Remember to test your library thoroughly and keep it well-documented for ease of use.