Integrating Java code into environments like Unity, which primari uses C#, often requires packaging Java classes into a JAR (Java Archive) file. This guide outlines the process of configuring an Android Studio project to generate a Java library and extract the necessary JAR for C# applications.
Setting Up an Android Studio Project as a Library Module
- Launch Android Studio and initiate a new project. Choose the "No Activity" or "Empty Activity" template to focus on creating a foundational library module.
- Configure the Project: Provide a suitable project name, package identifier, and storage location. After setup, allow Android Studio to complete the initial build process.
By default, a new project often creates an application module. To convert it into a reusable library, modifications to its build.gradle file are necessary.
-
Modify
build.gradle: Navigate to thebuild.gradle (Module :app)file in your project's structure. Change the plugin declaration fromcom.android.applicationtocom.android.library. Additionally, remove application-specific configurations such asapplicationId,versionCode, andversionNamefrom thedefaultConfigblock, as these are not relevant for a library. After making these changes, click "Sync Now" to apply the updated configuration.// Before modification: // apply plugin: 'com.android.application' // ... // defaultConfig { // applicationId "com.example.myapp" // minSdkVersion 21 // targetSdkVersion 30 // versionCode 1 // versionName "1.0" // testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" // } // After modification: apply plugin: 'com.android.library' android { compileSdkVersion 30 buildToolsVersion "30.0.3" defaultConfig { minSdkVersion 21 targetSdkVersion 30 versionCode 1 // Optional, can be removed for pure library versionName "1.0" // Optional, can be removed for pure library testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } dependencies { implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.3.0' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' }
Developing the Java Library Class
Create a new Java class within your project's java directory. This class will contain the logic you intend to expose to C#.
The example below demonstrates various elements: static fields, instance fields, static methods (with and without return values), and instance methods (with and without return values). The android.util.Log class is used for logging, which is typical in Android development.
package com.example.crossplatformlib;
import android.util.Log;
public class MyCrossPlatformUtils {
// Static field: accessible directly via the class
public static String LOG_CATEGORY_TAG = "LIB_DEBUG";
// Instance field: accessible via an object instance
public String currentStatusMessage = "Initialization complete";
/**
* Static method to update the global logging tag.
* @param newTag The new tag string.
*/
public static void setLoggingCategory(String newTag) {
LOG_CATEGORY_TAG = newTag;
Log.d(LOG_CATEGORY_TAG, "Logging category updated to: " + newTag);
}
/**
* Static method to retrieve the current global logging tag.
* @return The current logging tag.
*/
public static String getLoggingCategory() {
Log.d(LOG_CATEGORY_TAG, "Retrieving logging category: " + LOG_CATEGORY_TAG);
return LOG_CATEGORY_TAG;
}
/**
* Instance method to set a specific status message for this utility object.
* @param message The status message string.
*/
public void setStatusMessage(String message) {
this.currentStatusMessage = message;
Log.d(LOG_CATEGORY_TAG, "Instance status message set: " + message);
}
/**
* Instance method to retrieve the status message from this utility object.
* @return The current status message.
*/
public String getStatusMessage() {
Log.d(LOG_CATEGORY_TAG, "Retrieving instance status message: " + this.currentStatusMessage);
return this.currentStatusMessage;
}
/**
* Simple instance method for integer addition.
* @param valA First integer operand.
* @param valB Second integer operand.
* @return The sum of valA and valB.
*/
public int addNumbers(int valA, int valB) {
Log.d(LOG_CATEGORY_TAG, "Adding " + valA + " and " + valB);
return valA + valB;
}
}
Building the Project and Extracting the JAR
After developing your Java library class, the next step is to build the project and obtain the compiled JAR file.
-
Build the Project: In Android Studio, select "Build" > "Make Project". This action compiles your Java code and generates an Android Archive (AAR) file.
-
Locate the AAR File: The generated AAR file can typically be found in your project directory under
app/build/outputs/aar/. The file will have a name similar toapp-debug.aarorapp-release.aar.An AAR file is essentially a specialized ZIP archive. It contains not only the compiled Java codee (
classes.jar) but also Android resources (like layouts, drawables), theAndroidManifest.xml, and other metadata. For C# integration (especially in Unity for Android targets), only theclasses.jaris usually required. -
Extract the JAR:
- Make a copy of the
.aarfile and rename its extension to.zip(e.g.,app-debug.aarbecomesapp-debug.zip). - Extract the contents of this ZIP file to a temporary directory.
- Inside the extracted folder, you will find
classes.jar. Thisclasses.jarcontains all the compiled bytecode of your Java library. This is the file you need for C# integration.
- Make a copy of the
Integrating into a C# Project (e.g., Unity)
To make the Java library accessible within a C# development environment like Unity, place the extracted classes.jar file in the correct location.
- Copy
classes.jar: Take theclasses.jarfile you extracted. - Place in Unity Project: In your Unity project, navigate to the
Assetsfolder and then toPlugins/Android. If this directory structure does not exist, create it:Assets/Plugins/Android/. Place theclasses.jarfile directly into thisAndroidfolder.
Unity will automatically detect the JAR file in this specific directory and include it when building for the Android platform, making its classes and methods accessible from C# scripts using Unity's AndroidJavaClass and AndroidJavaObject APIs.