Android add java library

Creating libraries for Android applications — Tutorial

1. Android library projects and Java libraries

Android project can use code contained in JAR files (Java libraries)

If you want to use libraries, these must only use API available in Android. For example, the java.awt and javax.swing packages are not available on Android.

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.

Читайте также:  Java string format ведущие нули

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.

2. 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 .

3. Prerequisite

The following example assumes that you have created an Android project with the com.example.android.rssfeed top level package based on the following tutorial: https://www.vogella.com/tutorials/AndroidFragments/article.html#fragments_tutorial

4. Exercise: Create an Android library module

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 .

Selection for creating a library project

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

Setting the library property

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

Setting the library property

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 o">+ 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 ListRssItem> parse(String rssFeed)  ListRssItem> 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

Define dependency in Android Studio - Select module

Define dependency in Android Studio - Select module

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  ..// everything as before // triggers update of the details fragment public void updateDetail(String uri)  // (1) ListRssItem> 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 .

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`

Источник

How to add external libraries to Android Project in Android Studio?

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- The ways to use external libraries

You are developing an Android app on Android Studio, sometimes you want to use an external library for your project, such as a jar file.

Common langs is an java library with open source code which is provided by the Apache, it has utility methods for working with String, numbers, concurrency .

Suppose that you want to use this library for your Android project. And using one of its utility methods to test whether a String is a number or not.

 import org.apache.commons.lang3.StringUtils; public class CheckNumeric < public void test() < String text1 = "0123a4"; String text2 = "01234"; boolean result1 = StringUtils.isNumeric(text1); boolean result2 = StringUtils.isNumeric(text2); System.out.println(text1 + " is a numeric? " + result1); System.out.println(text2 + " is a numeric? " + result2); >> 
  1. Add your jar files to libs folder of the project and declare it as a library to use.
  2. Create a Android module and copy your jar file to this module, and then declare your project using the newly created module.
  3. Declare and use a remote library.

2- Way 1 — Copy external library to libs folder

Turn back to «Android» Tab, you can see that your library has been already declared in build.grade (Module: app)

3- Way 2 — Using the module library

Suppose you have a AddLibsDemo2 project, you want to use common-lang3-3.4.jar library for this project.

Next, you need to declare the dependency of the main project into the newly created module.

4- Way 3 — Using remote library

Android Studio can use the library on a network, it is located in some repository on the Internet. Suppose you have AddLibDemo3 project, and you need to add the remote library to your project.

View more Tutorials:

These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.

  • Android Beginners Guide To Create A Weather Forecast App
  • * * The Complete Android Oreo(8.1) , N ,M and Java Development
  • Absolute Java Basics for Android
  • Android App & Game Development :Build 6 Android Apps & Games
  • Android and iOS Apps for Your WordPress Blog
  • Unity 3d Game Development — iOS, Android, & Web — Beginners
  • Learn Android Development From Scratch
  • Ultimate Coding Course for Web App and Android Development
  • The Complete Android™ Material Design Course
  • Unity Android Game Development : Build 7 2D & 3D Games
  • Advance Android Programming — learning beyond basics
  • Publish Games on Android, iTunes, and Google Play with UE4
  • Learning Path:Android:Application Development with Android N
  • The Android Crash Course For Beginners to Advanced
  • Android development quick start for beginners
  • Android App Development and Design
  • Developing High Quality Android Applications
  • Become an iOS/Android Game Developer with Unity 2017
  • The Complete Android & Java Developer Course — Build 21 Apps
  • Learning Path: Android: App Development with Android N
  • The Complete Android App Development
  • Create Android & iOS Apps Without Coding
  • Develop Your First 2D Game With Unity3D for Android
  • Full Stack Mobile Developer course ( iOS 11, and Android O )
  • Develop Android Apps using Python: Kivy

Источник

Как добавить внешние библиотеки в Android Project в Android Studio?

Следуйте за нами на нашей фан-странице, чтобы получать уведомления каждый раз, когда появляются новые статьи. Facebook

1- The ways to use external libraries

Вы разрабатываете приложение Android на Android Studio, иногда вы хотите использовать внешнюю библиотека для своего project, например файл jar.

Common Langs это библиотека java с открытым исходным кодом предоставленный Apache, имеет утилиты для работы с String, числами, concurrency .

Например вы хотите использовать эту библиотеку для вашего project Android. И использовать один из методов для проверки является ли текст числом или нет.

 import org.apache.commons.lang3.StringUtils; public class CheckNumeric < public void test() < String text1 = "0123a4"; String text2 = "01234"; boolean result1 = StringUtils.isNumeric(text1); boolean result2 = StringUtils.isNumeric(text2); System.out.println(text1 + " is a numeric? " + result1); System.out.println(text2 + " is a numeric? " + result2); >> 
  1. Добавить ваш файл jar в папку libs в project и объявить его как библиотеку для использования.
  2. Создать Android Module и копировать ваш файл jar в этот module, потом объявить ваш project использует только что созданный module.
  3. Объявить и использовать удаленную библиотеку.

2- Way 1 — Copy external library to libs folder

Вернитесь к Tab «Android», вы увидите что ваша библиотека объявлена в build.grade (Module: app)

3- Way 2 — Using the module library

Например у вас есть project AddLibsDemo2, и вы хотите использовать common-lang3-3.4.jar для этого project.

Далее вам нужно объявить зависимость главного project от только что созданного Module.

Вы можете проверить ваш Module который был объявлен в build.grade (Module: app).

4- Way 3 — Using remote library

Android Studio может использовать библиотеку в сети, она находится в каком-то репозитории (repository) в Интернете. Например у вас есть project AddLibDemo3, и вам нужно добавить библиотеки в сети в ваш project.

View more Tutorials:

Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.

  • Android Beginners Guide To Create A Weather Forecast App
  • * * The Complete Android Oreo(8.1) , N ,M and Java Development
  • Absolute Java Basics for Android
  • Android App & Game Development :Build 6 Android Apps & Games
  • Android and iOS Apps for Your WordPress Blog
  • Unity 3d Game Development — iOS, Android, & Web — Beginners
  • Learn Android Development From Scratch
  • Ultimate Coding Course for Web App and Android Development
  • The Complete Android™ Material Design Course
  • Unity Android Game Development : Build 7 2D & 3D Games
  • Publish Games on Android, iTunes, and Google Play with UE4
  • Advance Android Programming — learning beyond basics
  • Learning Path:Android:Application Development with Android N
  • The Android Crash Course For Beginners to Advanced
  • Android development quick start for beginners
  • Android App Development and Design
  • Developing High Quality Android Applications
  • Become an iOS/Android Game Developer with Unity 2017
  • The Complete Android & Java Developer Course — Build 21 Apps
  • Learning Path: Android: App Development with Android N
  • The Complete Android App Development
  • Create Android & iOS Apps Without Coding
  • Full Stack Mobile Developer course ( iOS 11, and Android O )
  • Develop Your First 2D Game With Unity3D for Android
  • Android Internals and Working with the source

Источник

Оцените статью