Can android use java libraries

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.

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.

Читайте также:  Удаление файлов в папке java

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`

Источник

Using Android Java libraries in Xamarin Forms – a practical example.

jenx.si

jenx.si

Android ecosystem has huge numbers of libraries which can be used in Android-based applications. Technically, these libraries are files with .jar or .aar extensions. When developing Android application with Java these libraries can be directly included/linked in the application and used. Of course, re-usage of these java-based libraries in Xamarin Forms is possible, but the process is not so straightforward.

In this blog post I will show how to import Android Java library into Xamarin Forms and use its functionality in C# application.

To make all more real-word, I will try to import one random jar library from public repository https://mvnrepository.com and try to use the logic from it.

Let’s get our hands dirty

As I sad before, for the purpose of this demo I randomly picked one library from mentioned repository. I picked HTML parser library located here https://mvnrepository.com/artifact/org.jsoup/jsoup. You can find more information and documentation about the library here https://jsoup.org.

First, In Visual Studio 2019 I create new Xamarin.Forms project with Blank Template. I select only Android platform. In one of the next blog posts I will show similar procedure for iOS – how to reuse Objective-C iOS code (and .a library) in Xamarin Forms and C#. But for now, let’s focus on Android.

new blank xamarin forms project

As usual, Visual Studio scaffolds two projects, one is Common Project (cross-platform shared code) and the other is Android specific project. Next, I add new “Android Binding Library (Xamarin)” project to handle bindings between imported Java library and C#/Xamarin runtime. This binding library will create proxies (or Managed Callable Wrappers or just wrappers for that mater) which will handle C# calls and delegate them to external Java library.

adding new Android Bindings Library project

My solution structure now consists of three projects:

New Xamairn Forms Bindings project on place.

I have everything ready and prepared so I can start putting external “logic” in my app.

Importing external Android Java library

I download latest version of jsoup library from https://mvnrepository.com/artifact/org.jsoup/jsoup/1.12.1. I also check maven definition for any dependencies. All library dependencies must be also embedded in the binding assembly . In my case, jsoup library has no dependencies, as you can see from maven definition below:

Mvnrepositry with Android Java library.

Procedure is simple, download jar file, put it into Jars folders in bindings project, mark file as “EmbeddedJar” and that’s it.

How to use EmbeddedJar in my project

Now, things start to get interesting. At project compile, EmbeddedJar build action/process starts to create endpoint/stubs between C# and Java. This are so called Managed Callable Wrappers.

If you know that your Java library is available on the target device, you can also use InputJar option for Build Action.

Almost always, when I do first compile I get a lot of compile errors, just like pictured below:

Errors after first compile

Due to differences between Java and C#, no all Java-to-C# relations can be translated 1:1. Normally, I observed each and every error and I just remove problematic code. For this purpose Transformation/Metadata.xml file with developer-specific directives how to handle code generation (mapping Java code to C# wrappers) is used. You can check awesome documentation about this here: Metadata.xml Transform file. In my case, I simply removed problematic code, so my binding transformation file looks like this:

Источник

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