Android studio java jar

how to create library ( jar ) in android studio ? [duplicate]

I want to create some library that i will use in the future beside my current project.

I can’t find a way to create library in android studio.

How to do it on android ?

3 Answers 3

As introduction I would suggest you to peek into this conceptually simple tutorial. Basically you can start your own library module when you chose your project, without adding any Activity. Then you create your Java Class, usually with a View. When your library is ready, with all its business logic, you can glue everything inserting in the top level build gradle the instruction you are using a library, basically before you remove the following line, that is not needed for a library:

(This line in your gradle file is a unique application ID that looks like a Java package name, that identifies your app to the device you are running and in google play)

and then you change this line:

apply plugin: ‘com.android.name_library’

When you have a more structured project you can follow the official documentation As it is well explained the difference between a normal Application and a Library is:

An Android library is structurally the same as an Android app module. It can include everything needed to build an app, including source code, resource files, and an Android manifest. However, instead of compiling into an APK that runs on a device, an Android library compiles into an Android Archive (AAR) file that you can use as a dependency for an Android app module.

I would not encourage you to use solutions like web services that do it on your behalf, namely just copying/pasting your existing code. In fact a library often needs specific architectural choices, so is important to consider and learn different factors, is not just writing some business logic is quite complex to explain, but you can imagine that also the choice of what the user can see and modify can be crucial. Also should be as much as possible bug free, because once it is adopted could cause problems to the users. I remand you to a famous post, superbly written where you can find some solution to this aspect.

Источник

импорт библиотек jar в android-studio

Я пытаюсь добавить банку jtwitter в свой проект.

сначала я попытался сделать следующее:

при импорте файла jar я получаю следующую ошибку:

Я исследовал и обнаружил, что android-studio имеет некоторые проблемы, и что вы должны отредактировать build.gradle файл самостоятельно.

поэтому я попытался добавить это в свою сборку.Gradle в файл:

и получил сообщение об ошибке: cannot resolve symbol dependencies

другой вопрос, где будет папка libs. Означает ли это External Libraries ?

любая помощь будет наиболее полезна,

13 ответов

обновленный ответ для Android Studio 2

простой и правильный способ импортировать jar/aar в ваш проект-импортировать его как модуль.

New -> Module

выберите Import .JAR/.AAR пакета

выбрать .СОСУД./AAR файл и поставить имя модуля

добавить модуль как зависимость

  1. создать папку libs в папке приложения.
  2. добавить .файлы jar в папку libs.
  3. затем добавить .файлы jar для сборки приложения.зависимость от gradle.
  4. наконец-то синхронизировать проект с Gradle файлы.

1.Создать папки libs:

2.Добавлять.jar в папку libs:

Читайте также:  Android sdk manager gui

3.Редактировать приложения строить.зависимость gradle:

  • открыть приложение/сборка.Gradle в

4.Синхронизировать проект с Gradle файлы:

  • наконец-то добавить .файлы jar для вашего приложения.

обновление:

здесь я собираюсь импортировать org.затмение.ПАОЗ.клиент.mqttv3.файл jar в наш модуль приложения.

  1. скопировать файл jar и вставьте его в каталог библиотеки.

  1. нажмите Ctrl + Alt + Shift + s или просто щелкните значок структуры проекта на панели инструментов.

  1. затем выберите модуль для импорта .jar-файл, а затем выберите вкладку зависимости.

  1. нажмите значок плюс, затем выберите Файл зависимость

  1. выбрать .путь к файлу jar, нажмите OK, чтобы построить gradle.

  1. — наконец-то мы импортировали .файл jar в наш модуль.

удачи в кодировании.

Запуск Android Studio 0.4.0 Решена проблема импорта jar по

для тех, кто любит ручное редактирование Откройте приложение/сборка.Gradle в

Android Studio 1.0.1 не делает его более ясным, но это делает его как-то проще. Вот что сработало для меня:

1) Используя explorer, создайте’external_libs‘ (любое другое имя в порядке) внутри проект/приложение / src папку, где «проект» — это имя вашего проекта

2) скопируйте файл jar в эту папку «external_libs»

3) в Android Studio перейдите в файл — > проект Структура — > зависимости — > добавить — > зависимость файла и перейдите к файлу jar, который должен быть под’src / external_libs

3) Выберите файл jar, и нажмите кнопку ‘Ok’

теперь проверьте свою сборку.gradle (Module.app) скрипт, где вы увидите банку, уже добавленную в разделе «зависимости»

в проекте щелкните правой кнопкой мыши

вы можете следить за скриншоты ниже:

вот как вы добавляете файлы jar из внешних папок

1) Нажмите на файл и там вы нажмете на новый и новый модуль

2) появляется новое окно, в котором вы должны выбрать импорт .СОСУД./Пакет AAR .

3) Нажмите на опцию path в правом верхнем углу окна . И дайте весь путь файла JAR .

4) Нажмите кнопку Готово.

теперь вы добавили файл Jar, и вам нужно добавить его в зависимость для вашего проект приложения

1)Щелкните правой кнопкой мыши на папке app и там вы должны выбрать параметры модуля или F4

2)нажать на зависимость в правом верхнем углу текущего окна .

3)Нажмите на символ » + «и выберите » зависимость модуля», и он покажет вам существующие файлы JAR, которые вы включили в свой проект .

выберите тот, который вы хотите, и нажмите «OK / Finish»

Android Studio 1.0 упрощает добавление .библиотека файлов jar для проекта. Перейдите в файл>структура проекта, а затем нажмите на зависимости. Там вы можете добавить .JAR-файлы с Вашего компьютера в проект. Вы также можете искать библиотеки из maven.

Это то, как я только что сделал на Android Studio версии 1.0.2

  • Я создал папку libs на [ваш проект dir]\app\src
  • Я скопировал jtwitter.Джар (или yambaclientlib.Джар) в [ваш проект dir]\app\src\libs каталог
  • следующий путь по меню: Файл — > Структура Проекта — > Зависимости — > Добавить — > Зависимость От Файла, Android Studio открывает диалоговое окно, в котором вы можете drag & drop на jar библиотека. Затем я нажал OK.

в этот момент ш перестроит проект, импортирующий библиотеку и разрешающий зависимости.

здесь три стандартных подхода для импорта файла JAR в Android studio. Первый —традиционным способом, второй —стандартным способом, и удаленный библиотека. Я объяснил эти подходы шаг за шагом со скриншотами по ссылке:

надеюсь, это поможет.

Если код для вашей библиотеки jar находится на GitHub, то импорт в Android Studio легко с JitPack.

вам просто нужно будет добавить репозиторий для сборки.Gradle в:

а затем репозиторий GitHub библиотеки как зависимость:

JitPack действует как репозиторий maven и может использоваться как Maven Central. Хорошо, что вам не нужно загружать банку вручную. За кулисами JitPack проверит исходный код из GitHub и скомпилировать его. Поэтому он работает только в том случае, если в репо есть файл сборки (build.Gradle в).

Читайте также:  Галерея изображений для android

появилась руководство о том, как подготовить проект Android.

Я вижу так много сложных ответов.

все это смутило меня, когда я добавлял свой файл Aquery jar в новую версию Android Studio.

вот что я сделал :

копировать вставил файл jar в папку libs, которая отображается в представлении проекта.

и в построении.файл gradle только что добавил эту строку: compile files(‘libs/android-query.jar’)

PS: после загрузки файла jar, пожалуйста, измените его имя. Я изменил имя на android-query.Джар

избежать избыточности. Если у вас есть jars под /libs в сборке приложения.gradle по умолчанию у вас будет

этого достаточно, чтобы добавить все банки, которые у вас есть под /libs

Я также столкнулся с тем же препятствием, но не смог найти решение из заданных ответов. Может быть это происходит из-за пути проекта, который имеет специальные символы и пространства и т. д. Поэтому, пожалуйста, попробуйте добавить эту строку в ваш build.gradle .

«..» (Double dot) найдет корневой каталог вашего проекта.

Источник

How to add a jar in External Libraries in Android Studio?

I am new to Android Studio.
How can I add a few jar files in the External Libraries below the folder?

16 Answers 16

A late answer, although I thought of giving an in-depth answer to this question. This method is suitable for Android Studio 1.0.0 and above.

STEPS

  1. First switch your folder structure from Android to Project.

  1. Now search for the libs folder inside the app folder.

  1. Once you have pasted the .jar file inside libs folder. Right click on the jar file and at end click on Add as library. This will take care of adding compile files(‘libs/library_name.jar’) in build.gradle [You don’t have to manually enter this in your build file].

Now you can start using the library in your project.

Add your jar file to the folder app/libs . Then right click the jar file and click «add as library».

If there is no libs folder you can create it. Click on the combo box that says «Android», and change it to «Project»

From here, you can right click on «apps» in the directory tree and go to «New» => «Directory»

Put your JAR in app/libs, and in app/build.gradle add in the dependencies section:

Create «libs» folder in app directory copy your jar file in libs folder right click on your jar file in Android Studio and Add As library. Then open build.gradle and add this:

Step 1: Download any JAR file for your Project.

Step 2: Copy .jar file and past in libs folder.

Step 3: Click on File > Project Structure >Select app > Dependencies

Step 4:

Step 5:

Step 6: After click Ok button then we can see the Dependencies add like this way:

In Android Studio version 3.0 or more I have used bellow like :

  1. Create libs to the app directory if not exist folder like
  • Set Project view in upper left corner
  • Go to project
  • Go to app
  • click on apps->New->Directory
  • name the folder libs
  • paste the jar to the libs folder
  • directory will look like bellow image

In build.gradle add these lines

Example with Parse jar.

Add jars to libs folder from Project view … create lib folder if not exists

Copy all jars there.

Add libs to gradle. in build.gradle file :

For add all jars of lib folder. change Parse-*.jar to *.jar

This is how you can add .jar file in Android Studio 2.1.3.

Читайте также:  Подсознание может все джон кехо аудиокнига для андроида

Copy the .jar file

paste the file in Libs folder and then right click on .jar file and press Add as library

open build.gradle

add lines under dependencies as shown in screenshot

Now press play button and you are done adding .jar file

The GUI based approach would be to add an additional module in your project.

  1. From the File menu select Project Structure and click on the green plus icon on the top left.
  2. The new Module dialog pops
  3. From the phone and tablet application group select the «Import JAR or AAR package» option and click next.
  4. Follow the steps to create a new module that contains your JAR file.
  5. Click on the entry that corresponds to your main project and select the dependencies tab.
  6. Add a dependency to the module that you created in step 4.

One final piece of advice. Make sure that the JAR file you include is build with at most JDK 1.7. Many problems relating to error message «com.android.dx.cf.iface.ParseException: bad class file magic (cafebabe) or version (0034.0000)» root straight to this :0.

A simple way to add Jar file Android Studio Steps:

  1. Copy and paste your jar file to libs folder of your project.
  2. Click File from File menu -> Project Structure (CTRL + SHIFT + ALT + S on Windows/Linux, ⌘ + ; on Mac OS X).
  3. Select Modules at the left panel -> Dependencies tab.
  4. Add. → Project Library → Attach Jar.

If anyone is looking for another solution without actually copying the jar file(s) into the project directory, e.g. when using a jar in multiple projects:

Open build.gradle and add

Note that of course you don’t have to use the myJarFolder variable, I find it useful though. The path can also be relative, e.g. ../../Path/To/My/Jars.
Tested with AndroidStudio 3.0

Update: For Gradle Plugin > 3.0 use implementation instead of compile:

  1. Create libs folder under app folder and copy jar file into it.
  2. Add following line to dependcies in app build.gradle file:

If you dont see option «Add as Library», make sure you extract (unzip) your file so that you have mail.jar and not mail.zip .

Then right click your file, and you can see the option «Add as library».

Please provide the jar file location in build.gradle

To add single jar file

Note: compile is deprecated in latest gradle, hence use implementation instead.

The «official way» to add a jar into your android project as an external library, is to add the jar in dependencies section in build.gradle.

If you’ve done all of the above, and none of the above works, then there are two other possibilities:

  1. If Android Studio or some other IDE doesn’t give red underlined errors in editor but runs in error in the Java Compiler, CHECK YOUR JAR. Your jar may not have a proper Manifest included therefore the compiler doesn’t know what the jar can provide/don’t know it’s package name
  2. Maybe it’s folder structure is messed up. The folder structure doesn’t match with its package name. package a.b.c; should be matching to folder a > folder b > folder c.
  3. The package name has some conflict. (Trust me, this happened to me and it took hours to figure it out.)

However, if you are going with cordova, here are some tips of adding external jars.

«build-extras.gradle» is the better way to manage your gradle file.

Here are the steps to manage extra settings in cordova-based android project:

Источник

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