Support free tutorials



vogella training Training Books

Creating libraries for Android applications - Tutorial

Lars Vogel

Version 2.3

20.07.2015

Android Library Projects

This tutorial describes how to create and use library projects in Android. The tutorial is based on Android Studio.


Table of Contents

1. Android library projects and Java libraries
2. Using JAR files in Android
2.1. How to use JAR files
2.2. Adding a module dependency
2.3. Restrictions in using Java libraries
3. Custom Android library modules
3.1. Using custom library modules
3.2. Priorities for conflicting resources
4. Creating custom Android library modules in Android Studio
5. Android library project
6. The support libraries from Google
6.1. Scope of the support libraries
6.2. Which support libraries are available
6.3. Using the support libraries in Eclipse
7. Prerequisite
8. Exercise: Create Android library module
8.1. Target
8.2. RSS - Really Simple Syndication
8.3. Using Android Studio: Create library module
8.4. Create the model class
8.5. Create instances
8.6. Android Studio: Define dependency to the library project
8.7. Use library project to update detailed fragments
8.8. Validate implementation
9. About this website
10. Links and Literature
10.1. Android library resources
10.2. vogella GmbH training and consulting support

1. Android library projects and Java libraries

Android project can use code contained in JAR files (Java libraries). It is also 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.

2. Using JAR files in Android

2.1. How to use JAR files

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. Depending on your IDE this automatically makes your JAR available or your have to do an additional step.

2.2. Adding a module dependency

In Android Studio you have to

  • Right-click the JAR file in the libs folder and select Add as library.

  • Check that you have a new entry compile files('libs/YOURJAR.jar' in your build.gradle file.

  • To ensure that the change is picked up, perform a clean build.

2.3. Restrictions in using Java libraries

If you want to use libraries, these must only use API available in Android. For example, the Android libraries do not contain the java.awt and javax.swing user interface libraries, as Android has its own user interface toolkit.

Library projects cannot be compiled to Android applications and started without another project using them.

Using library projects helps you to structure your application code. Also more and more important Open Source libraries are available for Android. Understanding library projects is therefore important for every Android programmer.

3. Custom Android library modules

3.1. Using custom library modules

If an Android application project uses an Android library module, the Android development tools include the code and resources from the library project into the build result of the Android project. This means, that the components, code and resources of the library project are compiled and packaged into the .apk file of the compiled application.

Therefore a library module can be considered to be a compile-time artifact. An Android library module can contain Java classes, Android components and resources. Only assets are not supported.

To create a library project, set the Mark this project as library flag in the Android project generation wizard.

The library project must declare all its components, e.g., activities, service, etc. via the AndroidManifest.xml file. The application which uses the library must also declare all the used components via the AndroidManifest.xml file.

3.2. Priorities for conflicting resources

The Android development tools merges the resources of a library project with the resources of the application project. In the case that a resource's ID is defined several times, the tools select the resource from the application, or the library with highest priority, and discard the other resource.

4. Creating custom Android library modules in Android Studio

To create a new libary module in Android Studio, select FileNew Module and select Android Library.

5. Android library project

The Android team introduced a new 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. This allows that an AAR file is included in the build process of an Android application similar to a JAR file

Warning

This AAR format is currently directly support by the Eclipse IDE. Stare on the following issue so that Google solves this issue: Allows Eclipse ADT plugin to work with .AAR files .

Tip

It is still possible to use AAR files with Eclipse. You can either convert them to to Android library projects as described in Consuming AARs from Eclipse blog post about it.

or use the Android Maven plug-in for your build.

6. The support libraries from Google

6.1. Scope of the support libraries

The Android Support Library package contains several libraries that supports new features or features of higher Android versions in earlier Android versions.

6.2. Which support libraries are available

You have different components here. At the time of this writing you have:

Table 1. Support library versions

Support Library Description Location
v4 Support Library Designed for Android 1.6 (API level 4) or higher. Includes lots of things including support for Fragments and the Loader framework. Located in the android-sdk/extras/android/support/v7/appcompat/ directory.
v7 Support Libraries Set of libraries which require Android 2.1 (API level 7) and higher. Requires also the v4 Support library.  
v7 appcompat library Adds support for the Action Bar. Includes also support for material design user interface. Located in the android-sdk/extras/android/support/v7/appcompat/
v7 cardview library Adds support for the CardView widget. android-sdk/extras/android/support/v7/cardview/
v7 recyclerview library Adds support for the RecyclerView widget. android-sdk/extras/android/support/v7/recyclerview/


To see a complete list of the available libraries see http://developer.android.com/tools/support-library/features.html.

6.3. Using the support libraries in Eclipse

You first need to download them via the Android SDK manager.

Copy the support libraries JAR file from its folder into the libs folder in your Android project.

For a more comprehensive description see http://developer.android.com/tools/support-library/setup.html

7. Prerequisite

The following example assumes that you have created a normal Android project called com.example.android.rssfeed based on the Android Fragments tutorial.

8. Exercise: Create Android library module

8.1. Target

Our library project will not contribute Android components but a 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. The format of the XML file is specified via the RSS specification.

Our library project will not contribute Android components but a data model and a method to get the number of instances. We will provide RSS-feed data. The following gives a short introduction into RSS.

8.2. RSS - Really Simple Syndication

An RSS document is an XML file which can be used to publish blog entries and news. The format of the XML file is specified via the RSS specification.

RSS stands for Really Simple Syndication (in version 2.0 of the RSS specification).

Typically a RSS file is provided by a web server, which RSS client read. These RSS clients parse the file and display it.

8.3. Using Android Studio: Create library module

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

Selection for creating a library project

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

Setting the library property

As template select that no activity should be created.

Setting the library property

As a result Android Studio shows another module.

Setting the library property

8.4. 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 + "]";
  }

} 

8.5. Create instances

Create a new class called RssFeedProvider with a static method to return a list of RssItem objects.

package com.example.android.rssfeedlibrary;

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

public class RssFeedProvider {
  // helper to get a list of RssItems

  public static List<RssItem> parse(String rssFeed) {

    List<RssItem> list = new ArrayList<RssItem>();
        Random r = new Random();
        Integer number = r.nextInt(10);
        for (int i = 0; i <number; i++) {
        // create sample data
            RssItem item = new RssItem("Summary "+i, "Description " +1);
            list.add(item);
        }
    return list;
  }
} 

Solve the TODOs to create example instances of the RssItem class and add it to the list. This method does currently only return test data.

8.6. Android Studio: Define dependency to the library project

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

Define dependency in Android Studio - Selecting dependency

Define dependency in Android Studio - Select module

Define dependency in Android Studio - Select module

8.7. Use library project to update detailed fragments

Use the static method of RssFeedProvider to get the list of RssItem objects and display the number in your DetailFragment instead of current system time.

To send the new data, change the updateDetail method in your MyListFragment class.

package com.example.android.rssreader;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.example.android.rssfeedlibrary.RssFeedProvider;
import com.example.android.rssfeedlibrary.RssItem;

import java.util.List;

public class MyListFragment extends Fragment {
  
  private OnItemSelectedListener listener;
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_rsslist_overview,
        container, false);
    Button button = (Button) view.findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        updateDetail();
      }
    });
    return view;
  }

  public interface OnItemSelectedListener {
      public void onRssItemSelected(String link);
    }
  
  @Override
    public void onAttach(Activity activity) {
      super.onAttach(activity);
      if (activity instanceof OnItemSelectedListener) {
        listener = (OnItemSelectedListener) activity;
      } else {
        throw new ClassCastException(activity.toString()
            + " must implement MyListFragment.OnItemSelectedListener");
      }
    }

    // triggers update of the details fragment
    public void updateDetail() {
        List<RssItem> list = RssFeedProvider
                .parse("http://www.vogella.com/article.rss");
        String text = String.valueOf(list.toString());
        listener.onRssItemSelected(text);
    }


} 

8.8. Validate implementation

Start your application and ensure that the toString value of the (at the moment randomly generated) list of RssItems is displayed in the detailed fragment.

9. About this website

10. Links and Literature

10.1. Android library resources

Google guide to install the support libraries

10.2. vogella GmbH training and consulting support

TRAINING SERVICE & SUPPORT
The vogella company provides comprehensive training and education services from experts in the areas of Eclipse RCP, Android, Git, Java, Gradle and Spring. We offer both public and inhouse training. Whichever course you decide to take, you are guaranteed to experience what many before you refer to as “The best IT class I have ever attended”. The vogella company offers expert consulting services, development support and coaching. Our customers range from Fortune 100 corporations to individual developers.