How to make a .jar out from an Android Studio project - java

I'm using AndroidStudio and I have this project as shown:
What is inside the blue circle is myLib. myLib also needs to use an external lib that is inside the red circle, and an apache package (green circle).
So I want to make this whole thing become a single .jar, so I can use it in another projects.
A step-by-step guide would be really appreciated, I'm a beginner in the developer world.
Thanks!

Open build.gradle for library project
Write two tasks in build.gradle -- deleteJar and createJar and add rule createJar.dependsOn(deleteJar, build)
The code from above:
task deleteJar(type: Delete) {
delete 'libs/jars/logmanagementlib.jar'
}
task createJar(type: Copy) {
from('build/intermediates/bundles/release/')
into('libs/jars/')
include('classes.jar')
rename('classes.jar', 'logmanagementlib.jar')
}
createJar.dependsOn(deleteJar, build)
Expand gradle panel from right and open all tasks under yourlibrary->others. You will see two new tasks there -- createJar and deleteJar
Double click on createJar
Once the task run successfully, get your generated jar from path mentioned in createJar task i.e. libs/xxxx.jar
copy the newly generated jar into your required project's lib folder-->right click-->select "add as library"

If you set up the code as a plain Java module in Gradle, then it's really easy to have Gradle give you a jar file with the contents. That jar file will have only your code, not the other Apache libraries it depends on. I'd recommend distributing it this way; it's a little weird to bundle dependencies inside your library, and it's more normal for users of those libraries to have to include those dependencies on their own (because otherwise there are collisions of those projects are already linking copies of the library, perhaps of different versions). What's more, you avoid potential licensing problems around redistributing other people's code if you were to publish your library.
Take the code that also needs to be compiled to a jar, and move it to a separate plain Java module in Android Studio:
File menu > New Module... > Java Library
Set up the library, Java package name, and class names in the wizard. (If you don't want it to create a class for you, you can just delete it once the module is created)
In your Android code, set up a dependency on the new module so it can use the code in your new library:
File > Project Structure > Modules > (your Android Module) > Dependencies > + > Module dependency. See the screenshot below:
Choose your module from the list in the dialog that comes up:
Hopefully your project should be building normally now. After you do a build, a jar file for your Java library will be placed in the build/libs directory in your module's directory. If you want to build the jar file by hand, you can run its jar build file task from the Gradle window:

In the Android Studio IDE, access the "Run Anything bar" by:
CTRL+CTRL +gradle CreateFullJarRelease+ENTER
After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar
OR
Gradle has already a Task for that, in the gradle side-menu, under the other folder.
Then scroll down to createFullJarRelease and click it.
After that you'll find your artefact in this folder in your project
Build > Intermediates > Full_jar > Release > CreateFullJarRelease > full.jar

Simply add this to your java module's build.gradle. It will include dependent libraries in archive.
mainClassName = "com.company.application.Main"
jar {
manifest {
attributes "Main-Class": "$mainClassName"
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}
}
This will result in [module_name]/build/libs/[module_name].jar file.

task deleteJar(type: Delete) {
delete 'libs/mylibrary.jar'
}
task exportjar(type: Copy) {
from('build/intermediates/compile_library_classes/release/')
into('libs/')
include('classes.jar')
rename('classes.jar', 'mylibrary.jar')
}
exportjar.dependsOn(deleteJar, build)

Go to Gradle tab in Android Studio , then select library project .
Then go to Tasks
Then go to Other
Double click on bundleReleaseaar
You can find your .aar files under your_module/build/outputs/aar/your-release.aar

I had a supplement;
In the new version Android Studio(for me is: Android Studio Arctic Fox | 2020.3.1 Patch 3
Build #AI-203.7717.56.2031.7784292, built on October 1, 2021)
In gradle panel, it has no task in default.
Go to the Android Studio ---Settings--Experimental--Gradle tab, uncheck"Do not build Gradle task list during Gradle sync", then click File--Sync project with Gradle files, then the task appeared in the Gradle Panel.
Then follow the answer: https://stackoverflow.com/a/52681317/4065069

In case of this accepted answer not working for you
Use this
task createJar(type: Copy) {
from('build/intermediates/packaged-classes/release/')
into('libs/jars/')
include('classes.jar')
rename('classes.jar', 'plugin.jar')
}
Instead of this
task createJar(type: Copy) {
from('build/intermediates/bundles/release/')
into('libs/jars/')
include('classes.jar')
rename('classes.jar', 'logmanagementlib.jar')
}

the way i found was to find the project compiler output (project structure > project).
then find the complied folder of the module you wish to turn to a jar,
compress it with zip and change the extension of the output from zip to jar.

.jar file will be automatically generate when u compile/run your application.
You can find your class.jar file from root_folder/app/build/intermediates/bundles/debug

If you use
apply plugin: 'com.android.library'
You can convert .aar -> .jar
If you run a gradle task from AndroidStudio[More]
assembleRelease
//or
bundleReleaseAar
or via terminal
./gradlew <moduleName>:assembleRelease
//or
./gradlew <moduleName>:bundleReleaseAar
then you will able to find .aar in
<project_path>/build/outputs/aar/<module_name>.aar
//if you do not see it try to remove this folder and repeat the command
.aar[About] file is a zip file with aar extension that is why you can replace .aar with .zip or run
unzip "<path_to/module_name>.aar"

Related

How can you add dependency source code to sourceJar task output?

If you got a multi-project gradle build. And one module depends on another.
How could you add the dependency module source code to the output jar
Now i am using this:
java {
withSourcesJar()
}
I am new to gradle builds and i don't know any kotlin.
And if you have the source code of a dependency as a .jar file. Could you also add that
to the output?
So I have a project module:
dependencies:
project module
local .jar
What i want:
One .jar of the project (including other modules and dependencies) compiled code:
project-0.5.0.jar
..and one .jar of the source code (including other modules and dependencies)
project-0.5.0-sources.jar
I have all source code of dependencies stored locally as .jar files
Edit
My project conventions (global for all modules):
plugins {
`java-library`
}
java {
withSourcesJar()
}
How I am currently creating the project "fat".jar with compiled code:
(inside the build script)
tasks.jar {
//manifest.attributes["Main-Class"] = "com.example.MyMainClass"
val dependencies = configurations
.runtimeClasspath
.get()
.map(::zipTree) // OR .map { zipTree(it) }
from(dependencies)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
I have figured out how to add a project moduleA to another moduleB output sources .jar like so (inside moduleB's build-script):
tasks.sourcesJar {
from(project(":moduleA").sourceSets.main.get().allSource)
}
Now I need to figure out how to include source code from a dependency .jar
from(file("../path/dependency-1.0.0-sources.jar"))
This packs the .jar as it is. I need it's files.
I figured it out. And it was easier than i thought. Keep in mind i am using Kotlin.
(All code snippets are inside the build.gradle.kts file of the project / module you are creating the sources .jar for)
First off you need to include either the java or java-library plugin:
plugins {
`java-library`
}
And as far as i know, also this plugin extension:
java {
withSourcesJar()
}
This makes the sourcesJar task available (task used to create the sources jar), and you can modify it like so:
tasks.sourcesJar {
from(project(":common").sourceSets.main.get().allSource)
from(zipTree("../libs/tinylog-2.5.0/tinylog-api-2.5.0-sources.jar"))
}
The first line inside the brackets includes my "common" module source code to the output .jar.
The second line adds the .java files inside the tinylog sources .jar to the output .jar.

Gradle: multiple JARs without multiple projects

I have a library which is used to build a number of CLI tools using Gradle. Each CLI tool is a separate JAR. At the moment every tool requires a separate Gradle project, with an associated set of directories, like this:
Having all of this structure is resulting in the whole collection of tools becoming very unwieldy and difficult to work with. Is there any way to collect all of the different Mains into a single folder (suitably renamed) and configure Gradle to turn each one into a separate JAR?
FWIW, the JARs are currently created using https://github.com/johnrengelman/shadow . JAR size doesn't matter.
Thanks in advance.
Jars are just zip files with META-INF folder inside. Use Zip tasks to create them and dependsOn to run tasks as part of your build sequence.
I had the code like below for changing jar files:
task changeJar (type: Zip) {
baseName project.name
extension 'jar'
destinationDir new File('build')
entryCompression ZipEntryCompression.STORED
from { zipTree(new File(core.libsDir, core.name + '.jar')) }
from ( <somewhere else> ) {
exclude 'META-INF/'
}
}
I'm not sure if it's a good fit but you might be interested in my gradle-java-flavours plugin.
eg:
apply plugin: 'com.lazan.javaflavours'
javaFlavours {
flavour 'tool1'
flavour 'tool2'
}
dependencies {
compile 'a:a:1.0' // common to all tools
compileTool1 'b:b:2.0' // compile deps for tool1 only
runtimeTool2 'c:c:2.0' // runtime deps for tool2 only
}
Directories
src/main/java, src/test/java, src/main/resources, src/test/resources - common code & tests
src/tool1/java, src/testTool1/java, src/tool1/resources, src/testTool1/resources - tool1 only sources
src/tool2/java, src/testTool2/java, src/tool2/resources, src/testTool2/resources - tool2 only sources
Jars
projectName.jar
projectName-tool1.jar
projectName-tool2.jar

Creating a Java Gradle project and building the .jar file in IntelliJ IDEA - How to?

Is there a tutorial explaining how to properly create a Java Gradle project and build the .jar file?
When I create a Java project and add Gradle: File -> New -> Module -> Gradle -> ... I receive errors about Java EE websocket's not available (I'm using Ultimate Edition). However, I can successfully create a project by selecting File -> New -> Project-> Gradle -> which gives me a Java project with Gradle that I can debug. However, when I try to create an artifact (.jar file) I receive errors. I assume the errors stem from mistakes I made in the project structure settings.
Buildfile: build.xml does not exist!
Build failed
or
Error: Could not find or load main class Main
My project is such a mess at this point, maybe I should create another project, then copy/paste the Main.class and Gradle's dependencies from the old project onto the new project.
If this is my best option, how do I correctly create the project this time?
Create new Gradle (not Java) project. Be sure to select Java option in the dialog. Click Next.
fill GroupId, ArtifactId and version
Choose your gradle distribution. You can safely use the reccommended option.
Choose project name and location
Click finish
You put your java classes to src/main/java folder. When using third party libraries, make sure you declare them as Gradle dependencies.
You build your sources using Gradle tab → tasks → build (double click)
You can see the result of the build in the Run tab
In case of error, you can see details by clicking the following button:
Just incase you run into no main manifest attribute problem where the executable Jar file is not running, I do the following.
1: go to your build.gradle and add the following at the bottom.
jar {
manifest {
attributes 'Main-Class': 'your_package_name.YOUR_MAIN_CLASS'
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
go to View > Tool Windows > Gradle
A panel at the right side will be shown, now click the build for more task. Under the build task double click the build option and wait until the task is done.
Now, go to your project directory and open the build > libs and the executable Jar file will be there.
I'm not sure if this is the right way.
No need to accept if it works, hope this help the others.
Step 1: Add these lines on your build.gradle
jar {
from {
configurations.runtime.collect {
it.isDirectory() ? it : zipTree(it)
}
configurations.compile.collect {
it.isDirectory() ? it : zipTree(it)
}
}
manifest {
attributes 'Main-Class': 'YOUR MAIN CLASS'
}
exclude 'META-INF/*.RSA', 'META-INF/*.SF','META-INF/*.DSA'
}
Step 2: clean and build .
I'm sure it will work , Regards
If you are using Intellij you can just open the Gradle plugin (it is on the right side of your IDE) and execute a command: bootRepackage. With this you will have a jar in: your_project_folder/build/libs.

IntelliJ and Android Gradle dependencies - unable to find module

I have following directory structure:
D:\PROJECT
+---javaGradleProject1
+---javaGradleProject2
+---javaGradleProject3
\---AndroidProject
| build.gradle
| settings.gradle
\---AndroidModule
build.gradle
Android module depends on all of java gradle projects that are at the same level in root directory as AndroidProject.
In AndroidProject/settings.gradle I have:
include ':AndroidModule'
include 'javaGradleProject1'
project(':javaGradleProject1').projectDir = new File(rootDir, '../javaGradleProject1')
include 'javaGradleProject2'
project(':javaGradleProject2').projectDir = new File(rootDir, '../javaGradleProject2')
include 'javaGradleProject2'
project(':javaGradleProject2').projectDir = new File(rootDir, '../javaGradleProject2')
And then in AndroidProject/AndroidModule/build.gradle I have dependencies set like this:
compile project(':javaGradleProject1')
compile project(':javaGradleProject2')
compile project(':javaGradleProject3')
This structure of dependency perfectly works and project builds when I invoke
gradle build
on AndroidProject/build.gradle.
But when I try to synchronize my IntelliJ with current gradle dependency settings I receive
Error: Unable to find module with Gradle path ':javaGradleProject1'
Error: Unable to find module with Gradle path ':javaGradleProject2'
Error: Unable to find module with Gradle path ':javaGradleProject3'
and because of that my project cannot be run from Run Configurations (it does not compile at all in IDE). I was trying to add these dependencies manually by hitting F4 and module dependencies but after synchronization all of my changes are overwritten (actually, IntelliJ just removes it).
Is there anything wrong in my gradle structure?
I have tested it on IntelliJ IDEA 14.1.4 and Android Studio 1.3.
I was able to solve this by deleting the settings.gradle file from every Gradle project that I wanted to use as dependency (clearing the contents of this file was not enough).
NOTE: As I have little knowledge of Gradle and Android Studio, I cannot provide information about why the presence of this file does not allow Android Studio to include the Gradle project as a module.
Add a colon (:) before the names of your modules when you add it in settings.gradle, e.g. for the first one, change this:
include 'javaGradleProject1'
project(':javaGradleProject1').projectDir = new File(rootDir, '../javaGradleProject1')
to this:
include ':javaGradleProject1'
project(':javaGradleProject1').projectDir = new File(rootDir, '../javaGradleProject1')
Now in addition to compiling, IntelliJ / Android Studio should give you code completion.
In my case I had to change the external module name to lowercase only.
Right click project, Select
"Configure Project Subset ..."
and select your module, rebuild your project.
Tried all the available solutions, and in last I have commented the include ':app' in settings.gradle and this resolved the issue in my case
In my case non of the answers above resolved it.
Finally, I went to settings.gradle file and inside the dependencyResolutionManagement block, I changed the repositoriesMode to "PREFER_PROJECT"
repositoriesMode.set(RepositoriesMode.PREFER_PROJECT)
That was all I did and it worked like magic, maybe such can help you too, you can try it out.

How to create Android library in Android Studio [duplicate]

How do I create an Android Library Project (e.g. com.myapp.lib1) and the application project (e.g. com.myapp.app) and make the build system include com.myapp.lib1 on the application project?
I went to the Project Structure -> Modules -> My App project and added a dependency to the lib project. IntelliJ now can recognize classes from the lib project when used in the app project, but when I run the app project, there are errors like:
Gradle: error: package com.myapp.lib1 does not exist
I wonder why there is no example of stand alone jar project.
In eclipse, we just check "Is Library" box in project setting dialog.
In Android studio, I followed this steps and got a jar file.
Create a project.
open file in the left project menu.(app/build.gradle): Gradle Scripts > build.gradle(Module: XXX)
change one line: apply plugin: 'com.android.application' -> 'apply plugin: com.android.library'
remove applicationId in the file: applicationId "com.mycompany.testproject"
build project: Build > Rebuild Project
then you can get aar file: app > build > outputs > aar folder
change aar file extension name into zip
unzip, and you can see classes.jar in the folder.
rename and use it!
Anyway, I don't know why google makes jar creation so troublesome in android studio.
To create a library:
File > New Module
select Android Library
To use the library add it as a dependancy:
File > Project Structure > Modules > Dependencies
Then add the module (android library) as a module dependency.
Run your project. It will work.
Google’s Gradle Plugin recommended way for configuring your gradle files to build multiple projects has some shortcomings If you have multiple projects depending upon one library project, this post briefly explain Google’s recommended configuration, its shortcomings, and recommend a different way to configure your gradle files to support multi-project setups in Android Studio:
An alternative multiproject setup for android studio
A Different Way :
It turns out there’s a better way to manage multiple projects in Android Studio. The trick is to create separate Android Studio projects for your libraries and to tell gradle that the module for the library that your app depends on is located in the library’s project directory. If you wanted to use this method with the project structure I’ve described above, you would do the following:
Create an Android Studio project for the StickyListHeaders library
Create an Android Studio project for App2
Create an Android Studio project for App1
Configure App1 and App2 to build the modules in the StickyListHeaders project.
The 4th step is the hard part, so that’s the only step that I’ll describe in detail. You can reference modules that are external to your project’s directory by adding a project statement in your settings.gradle file and by setting the projectDir property on the ProjectDescriptor object that’s returned by that project statement:
The code one has to put in settings.gradle:
include ':library1'
project(':library1').projectDir = new File('../StickyListHeader/library1')
If you’ve done this correctly, you’ll notice that the modules referenced by your project will show up in the project navigator, even if those modules are external to the project directory:
This allows you to work on library code and app code simultaneously. Version control integration also works just fine when you reference modules externally this way. You can commit and push your modifications to the library code just like you can commit and push modifications to your app code.
This way of setting up multiple projects avoids the difficulties that plague Google’s recommended configuration. Because we are referencing a module that is outside of the project directory we don’t have to make extra copies of the library module for every app that depends on it and we can version our libraries without any sort of git submodule nonsense.
Unfortunately, this other way of setting up multiple projects is very difficult to find. Obviously, its not something you’ll figure out from looking at Google’s guide, and at this point, there’s no way to configure your projects in this way by using the UI of Android Studio.
Check out this link about multi project setups.
Some things to point out, make sure you have your settings.gradle updated to reference both the app and library modules.
settings.gradle: include ':app', ':libraries:lib1', ':libraries:lib2'
Also make sure that the app's build.gradle has the followng:
dependencies {
compile project(':libraries:lib1')
}
You should have the following structure:
MyProject/
| settings.gradle
+ app/
| build.gradle
+ libraries/
+ lib1/
| build.gradle
+ lib2/
| build.gradle
The app's build.gradle should use the com.android.application plugin while any libraries' build.gradle should use the com.android.library plugin.
The Android Studio IDE should update if you're able to build from the command line with this setup.
For Intellij IDEA (and Android Studio) each library is a Module. Think of a Module in Android Studio as an equivalent to project in Eclipse. Project in Android Studio is a collection of modules. Modules can be runnable applications or library modules.
So, in order to add a new android library project to you need to create a module of type "Android library". Then add this library module to the dependency list of your main module (Application module).
The simplest way for me to create and reuse a library project:
On an opened project file > new > new module (and answer the UI questions)
check/or add if in the file settings.gradle: include ':myLibrary'
check/or add if in the file build.gradle:
dependencies {
...
compile project(':myLibrary')
}
To reuse this library module in another project, copy it's folder in the project instead of step 1 and do the steps 2 and 3.
You can also create a new studio application project
You can easily change an existing application module to a library module by changing the plugin assignment in the build.gradle file to com.android.library.
apply plugin: 'com.android.application'
android {...}
to
apply plugin: 'com.android.library'
android {...}
more here
You can add a new module to any application as Blundell says on his answer and then reference it from any other application.
If you want to move the module to any place on your computer just move the module folder (modules are completely independent), then you will have to reference the module.
To reference this module you should:
On build.gradle file of your app add:
dependencies {
...
compile project(':myandroidlib')
}
On settings.gradle file add the following:
include ':app', ':myandroidlib'
project(':myandroidlib').projectDir = new File(PATH_TO_YOUR_MODULE)
Don't forget to use apply plugin: 'com.android.library' in your build.gradle instead of apply plugin: 'com.android.application'
Documentation Way
This is the recommended way as per the advice given in the Android Studio documentation.
Create a library module
Create a new project to make your library in. Click File > New > New Module > Android Library > Next > (choose name) > Finish. Then add whatever classes and resourced you want to your library.
When you build the module an AAR file will be created. You can find it in project-name/module-name/build/outputs/aar/.
Add your library as a dependency
You can add your library as a dependency to another project like this:
Import your library AAR file with File > New Module > Import .JAR/.AAR Package > Next > (choose file location) > Finish. (Don't import the code, otherwise it will be editable in too many places.)
In the settings.gradle file, make sure your library name is there.
include ':app', ':my-library-module'
In the app's build.gradle file, add the compile line to the dependencies section:
dependencies {
compile project(":my-library-module")
}
You will be prompted to sync your project with gradle. Do it.
That's it. You should be able to use your library now.
Notes
If you want to make your library easily available to a larger audience, consider using JitPac or JCenter.
Had the same question and solved it the following way:
Start situation:
FrigoShare (root)
|-Modules: frigoshare, frigoShare-backend
Target: want to add a module named dataformats
Add a new module (e.g.: Java Library)
Make sure your settings.gradle look like this (normally automatically):
include ':frigoshare', ':frigoShare-backend', ':dataformats'
Make sure (manually) that the build.gradle files of the modules that need to use your library have the following dependency:
dependencies {
...
compile project(':dataformats')
}
Purpose: Android library at single place - Share across multiple projects
http://raevilman.blogspot.com/2016/02/android-library-project-using-android.html
As theczechsensation comment above I try to search about Gradle Build Varians and I found this link: http://code.tutsplus.com/tutorials/using-gradle-build-variants--cms-25005
This is a very simple solution. This is what I did:
- In build.gradle:
flavorDimensions "version"
productFlavors {
trial{
applicationId "org.de_studio.recentappswitcher.trial"
flavorDimension "version"
}
pro{
applicationId "org.de_studio.recentappswitcher.pro"
flavorDimension "version"
}
}
Then I have 2 more version of my app: pro and trial with 2 diffrent packageName which is 2 applicationId in above code so I can upload both to Google Play. I still just code in the "main" section and use the getpackageName to switch between to version. Just go to the link I gave for detail.
There are two simplest ways if one does not work please try the other one.
Add dependency of the library inside dependency inside build.gradle file of the library u r using, and paste ur library in External Libraries.
OR
Just Go to your libs folder inside app folder and paste all your .jar e.g Library files there Now the trick here is that now go inside settings.gradle file now add this line "include ':app:libs'" after "include ':app'" It will definitely work...........:)
In my case, using MAC OS X 10.11 and Android 2.0, and by doing exactly what Aqib Mumtaz has explained.
But, each time, I had this message : "A problem occurred configuring project ':app'. > Cannot evaluate module xxx : Configuration with name 'default' not found."
I found that the reason of this message is that Android 2.0 doesn't allow to create a library directly. So, I have decided first to create an app projet and then to modify the build.gradle in order to transform it as a library.
This solution doesn't work, because a Library project is very different than an app project.
So, I have resolved my problem like this :
First create an standard app (if needed) ;
Then choose 'File/Create Module'
Go to the finder and move the folder of the module freshly created in your framework directory
Then continue with the solution proposed by Aqib Mumtaz.
As a result, your library source will be shared without needing to duplicate source files each time (it was an heresy for me!)
Hoping that this help you.

Categories

Resources