Android studio как подключить библиотеку
Перейти к содержимому

Android studio как подключить библиотеку

  • автор:

Подключение сторонней библиотеки в проект Android Studio

Какие шаги нужно выполнить, чтобы добавить чужой проект (библиотеку) к своему в Android Studio? Нужно, чтобы я мог обратиться из своего проекта к классам из чужого проекта. В build.gradle я уже прописал.

Во-первых, если библиотека достаточно выского качества, то автор библиотеки, как правило, дает инструкции о том, как ее подключить в свой проект — им надо следовать в первую очередь.

Сама Android Studio позволяет подключить три типа библиотек в свой проект:

из репозитория Maven

библиотеку в виде собранного .jar файла

библиотеку в виде исходных кодов

Для выполнения этой работы в Android Studio есть графический интерфейс, но олдскульные кодеры могут проделать ту же работу, прописывая необходимые команды в конфиги gradle вручную.
Открываем окно структуры проекта ( File -> Project Structure ) и переходим к основному модулю проекта — слева секция Modules, кликнуть по названию модуля вашего приложения (на скриншоте это app). В открывшемся окне переходим к вкладке Dependencies . Здесь вы можете управлять подключенными зависимостями: добавить новые, удалить ненужные и перемещать их по иерархии.

Структура проекта

Для того, чтобы добавить зависимость, нажимаем на плюсик справа и видим три пункта — рассмотрим их подробнее:

  1. Library dependency — добавление библиотеки из внешнего репозитория

Этот пункт требует, как правило, наименьшего количества усилий. Обычно, по умолчанию, в конфиге gradle всего проекта в качестве внешнего репозитория используется JCenter и все уважающие себя разработчики складывают свои труды туда, но вы можете прописать в том конфиге и другие репозитории с библиотеками, если таковые вам требуются.
При выборе пункта 1 появляется окно поиска, в котором вы можете набрать имя требуемой библиотеки и, если она присутствует в репозитории — вы ее увидите. Нажатие кнопки OK проделает всю черную работу по подключению библиотеки и после того, как gradle проведет необходимые манипуляции по скачиванию и импорту, она будет доступна в вашем проекте.

Выбор зависимых библиотек

Если вы не доверяете инструментам Android Studio и желаете самостоятельно вручную добавить библиотеку из репозитория, вам необходимо прописать в секции dependencies<> конфига build.gradle вашего приложения ссылку на нужную библиотеку:

При внесении каких-либо изменений в конфиги gradle вверху появляется предупреждение о необходимости синхронизировать проект — когда все изменения будут сделаны, нажмите на ссылку Sync Now вверху справа, чтобы gradle применил ваши изменения.

  1. File dependency — добавление библиотеки из локального скомпилированного .jar файла

Перед началом импорта локальной библиотеки в виде .jar файла необходимо скопировать сам файл библиотеки в папку /libs вашего проекта.
При выборе пункта 2 появится стандартный диалог выбора файла, в котором необходимо указать, собственно, сам файл подключаемой библиотеки.
При нажатии кнопки OK gradle проведет некоторые манипуляции по импорту, которые займут какое-то время, после чего библиотека будет доступна в вашем проекте.

Выбор пути

Для того, чтобы вручную сделать то же самое — добавить библиотеку на основе .jar файла, в секции dependencies<> конфига build.gradle приложения необходимо прописать следующее:

Для того, чтобы подключить все библиотеки из папки /libs/ разом, нужно сделать так:

  1. Module dependency — добавление библиотеки из исходных кодов

Перед импортом библиотеки из исходных кодов необходимо скачать сами исходные коды и распаковать в какой-то каталог.
Для наименьших проблем:

исходные коды должны быть gradle-проектом Android Studio/IntelliJ IDEA

имена основного модуля и модуля подключаемой библиотеки не должны совпадать.

подключаемый исходник является библиотекой, а не приложением (в build.gradle того, что вы подключаете указано apply plugin: ‘com.android.library’ ) — это можно исправить самостоятельно в конфиге gradle того, что вы подключаете.

минимальные версии SDK вашего проекта и библиотеки должны совпадать — можно исправить самостоятельно в конфигах gradle проекта или библиотеки.

версии BuildTools проекта и библиотеки должны совпадать (рекомендуется), либо обе версии должны быть установлены в вашем SDK (не рекомендуется). Лучшее решение — всегда использовать самую последнюю версию BuildTools

Для начала импортируем нужную библиотеку в свой проект в качестве модуля. Нажимаем File -> New -> Import Module , указываем путь до корневой папки с разархивированными исходниками и следуем другим указаниям мастера импорта.

Меню импорта модуля

После чего, выбрав пункт 3 (смотрите первый скриншот) появляется окно выбора модуля, кликнув по нужному и нажав кнопку OK будет проведена работа по импорту в ваш проект, после чего библиотека будет доступна в вашем проекте.

Добавление библиотеки на основе исходников вручную — несколько муторное занятие и описывать я его не буду. Ценители ручного способа конфигурации проекта получат удовольствие, проделав «таинство» самостоятельно, а остальным вовсе без надобности.

Android studio как подключить библиотеку

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

Существует несколько способов подключения библиотек. Разница между ними в следующем: в одном случае можно подключать библиотеки без отдельной загрузки файлов — библиотек; ну и другом случае нужно как то прилепить скачанные библиотеки к Android Studio.

Как подключить библиотеки прямиком к Android Studio? А вот так:

— Нужно убедиться, что у вас в загружено Android Support Repository. Просто заходим в Android SDK Manager и смотрим, есть ли этот файл в списке загруженных. Если нет — то качаем оттуда же с SDK Manager;

— Далее открываем файл build.gradle вашего приложения:

Настройка библиотек

— Теперь в открывшемся файле build.gradle нужно просто добавить в раздел dependencies нужную библиотеку.

Например, мы хотим добавить в свой проект библиотеку v4:

Вот еще 1 способ подключить к вашему приложению дополнительные библиотеки. В окне Android Studio идем по адресу File — Project Structure. В появившемся окне выбираем наше приложение и переходим во вкладку Dependencies:

Dependence

Справа видим зеленый значок плюса, жмем по нему и выбираем Library dependency. В появившемся окне нам предлагается либо выбрать из списка существующий популярных библиотек, либо ввести в строку поиска название нужной библиотеки для ее поиска, или же ее адрес местонахождения:

Выбор

Выбираем требуемую нам библиотеку и жмем ОК, и еще раз ОК. Происходит процесс подключения библиотеки и все, готово!

Есть еще способы подключения библиотек, как для меня морочные и просто ужасные, но как — нибудь попробую написать и о них.

How to use android libraries locally and leaving your development faster

In android development we have a problem that makes us a little frustrated every day, the build time . The android studio build time has a tendency to increase with each day that our project is getting bigger, with that isolating everything we will have in the one project, in a single module, and this is an option that is not so interesting, both to avoid rewriting code in a future project, both to avoid creating a liability relationship of some common feature .

One option for us to try resolve this is to create libraries, which are nothing more than independent modules which has an easy integration and has its responsibility defined and isolated, avoiding side effects and being portable for numerous cases.

To use this portability we need to take a few steps:

  1. Creating new project with sample module
  2. Creating the library module
  3. Importing the module created in an external project
  4. Sharing with community .

I am writing listening a brazilian band called Bullet Bane, in my posts i like share music in view of my great musical passion and the responsibility to disseminate more music around the world. So Let’s go code ..

1. Create new project with sample module

Creating libraries is a task that can be done at any time and in the way that you think necessary, my suggestion is to create them in an external project and thus removing any possibility of interdependence, enabling it to develop outside the scope of only one project and too create one identity to a common feature. So let’s go with my suggestion, create the new android project ..

With the new project created and its initial structure simple, with MainActivity and everything else, we will determine that this App module will be our sample module, which will be used to test the integration of our library, if you want rename the “App” module to “Sample” .

2. Create the library module

To create is a simple task, in Android Studio each library is a module. To create a new library module in Android Studio, select File ▸ New ▸ New Module and select Android Library .

When we create the library it is not automatically imported into our sample module, so simply go to the build.gradle of our sample module and add in the dependencies :

With this we can develop our feature in this created library module, with all its responsibilities much more clear, specific and without any complexity of a great project, without mentioning that clearly the build time of our sample module destined to be our workspace of this library is much faster than our main project. A great suggestion is also to add integration tests in the sample module and unit tests in your library module to ensure that it develops with complete security and consistence of its main and future functionalities.

3. Importing the module created in an external project locally

This task can be done automatically by Android Studio, but my suggestion is that you do it manually so that you understand the process clearly and can fit in case you need it.

3.1 Include module folder into project

Automatically is simple only in Android Studio, select File ▸ New ▸ Import Module and write path of library project and select only library module .

Manually it’s more cool, despite having to write some more but i think it more interesting to eliminate any magic that IDE makes and to facilitate understanding the process. Steps below ..

Add into settings.gradle and sync gradle .

3.2 Add library locally into project

Simply do same earlier step to add the module, add compile into build.gradle dependencies of main module .

PS : This process can cause some conflicts if the projects use other libraries in different versions, it is important to always keep the same of both libraries updated.

4. Sharing with community

There are many ways to distribute your library, but if your new library module has no business rule (as it should be), it is important to share it with the community. So that other people can use it to find bugs, fix them, develop new features for it. Thus creating an ecosystem of interaction with your library that will give much more powers to it .

I suggest https://jitpack.io/ to this, jitpack is very easy to use, follow the tutorial below and you will get it easily.

In STANT so far we are using 2 android libraries and we have other projects on other platforms, open-source and using this principle and has facilitated enough thing, internally the trend is to adopt even more is this idea.

Android studio как подключить библиотеку

Adding External Library in Android Studio

Adding an external library in Android Studio is a very common thing but still, most beginners or freshers find it difficult to do. So let’s learn how to add any external library to our Android Studio project and the pros & cons associated with it.

VIDEO TUTORIAL DEMO

Let’s discuss three ways of adding an external library as follows:

  1. Adding Gradle dependency.
  2. Adding .jar or .aar dependency.
  3. Adding dependency as a module.

1. Adding Gradle Dependency

It is very easy to add Gradle dependency. Most of us are familiar with this method as it is a common way and recommended too. Suppose you want to add Picasso to your project then you can add Gradle dependency as mentioned below to your project in build.gradle at the app level inside the dependencies block.

In the above implementation, 2.71828 is the latest version of the library. It will be different for different libraries and you can get it from respective Github repositories or release note’s pages.

Pros: If we need the updated version of the library we can directly see the latest version over its Github repository and replace it with the existing one and our library will be updated.

Cons: If you want to change any kind of code in the existing library then it’s not possible as it is read-only.

2. Adding .jar/.aar Dependency

In some cases, we don’t get the Gradle dependency of the library. Instead, we get only the .jar/.aar file. In such case you can follow the below steps:

  1. Find the .jar/.aar file and download it.
  2. Then copy the file from the downloaded location and go to Android Studio.
  3. Go to the App module and paste the file inside the libs folder. (If you don’t see the libs folder, create a new directory inside the App module.)
  4. After adding the file right-click on it and select Add As Library.

Pros: I don’t see any pro for this. As we only need to add any .jar/.aar dependency if the library provider doesn’t have any other way to do.

Cons:

  1. Here updating the library is a bit lengthy task as we again need to download the latest jar and follow the same steps as mentioned above.
  2. You cannot modify the code if you want to as the files are read-only.

3. Adding dependency as a module

There can be a situation when we need to modify the library code according to our requirement then in that case we can follow this method.

  1. Go to the Github repo link of the library you are looking for.
  2. Click on the green color Code dropdown button.

Pros: You can modify the code according to your requirement.

Cons: Getting the updated version of the library can be difficult since we are making code changes here.

So these are the three ways of adding any external library to the Android Studio project. Hope this will help you guys.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *