- Модульная разработка Android приложений
- Попробовали git submodule
- Осторожно, не все можно публиковать
- Итак, начинаем создавать модуль
- Настраиваем gradle для публикации в artifactory
- Настройка CI окружения
- Используем модуль в продукте
- С чем мы столкнулись
- Что в итоге получилось
- How to Add a Library Project to Android Studio?
- Different Ways To Add Library Project to Android Studio
- Method 1
- Method 2
- Method 3
- Method 4
- Adding external library in Android studio
- 19 Answers 19
Модульная разработка Android приложений
При разработке Android приложений наступают моменты, когда те или иные части кода можно вынести в виде библиотек, чтобы можно было переиспользовать их в разных проектах:
- Модули в проекте, которые часто встречаются. Например, кастомные View
- Когда существующий API неудобный или не позволяет сделать то, что задумали — создаем расширение для этого API
Чаще всего все проблемы были решены задолго до нас, но в нашем случае нужно было вынести часть слоя бизнес-логики и фактически весь слой, отвечающий за данные в 3 наших основных продукта объединенной компании Колёса Крыша Маркет. Все наши продукты – классифайды про автомобили, недвижимость и прочие товары. Поэтому нами, разработчиками, было решили написать одно решение для всех продуктов компании. К тому же, это облегчило нашу работу.
Попробовали git submodule
Самое простое решение — использовать git submodule. Если кратко объяснить его работу, то к git repository вы прикрепляете ссылку на другой git repository, который должен автоматически клонироваться вместе с родительским. Казалось бы все просто: у нас есть несколько git repository, где хранятся все наши модульные библиотеки и нужно всего лишь указать его в git submodule.
Но как быть с версиями? При обновлении через команду git submodule update стираются изменения в submodule, merge не происходит. Вам придется постоянно обновляться, когда другой разработчик вносит изменение в данном submodule. Вместо этого стоит разрабатывать модули в виде библиотек с jar файлом или Android Archive (aar). По факту, в этих архивах содержатся те же самые файлы, которые могли быть в git submodule, но теперь есть более понятное версионирование вместо истории commit или tag.
Осторожно, не все можно публиковать
При публикации библиотек стоить учесть, что они не должны содержать конфиденциальные данные компании. Более того, не будет удобно остальным разработчикам, если в библиотеке будет содержаться код, относящийся к конкретной компании. Следовательно, нам нужен закрытый artifactory для хранения библиотек в закрытом доступе. Есть множество open source решений, но мы используем JFrog Artifactory.
А если можно публиковать? В таком случае вас ждет светлая дорога в мир open source проектов. Достаточно просто найти открытые web серверы, которые поддерживают gradle, чтобы размещаемые jar и aar файлы подтягивались через dependency в ваших проектах.
Итак, начинаем создавать модуль
Начинается все просто — заходим в File > New > New Module…
Название библиотеки, которое укажете в этом окне, станет названием бинарника вашей библиотеки.
Создав модуль можете приступить к написанию кода. Если к прилагаемому коду будете писать тесты, остальным членам команды будет понятно, как вашим модулем пользоваться. Еще лучше, если создадите новый sample app module, который работает исключительно с вашим модулем для демонстрации на реальных устройствах. Удобнее, когда вам нужно предварительно протестировать код перед публикацией в artifactory. Для этого достаточно указать зависимость в build.gradle. В примерах я буду указывать librarymodule в качестве названия модуля.
Настраиваем gradle для публикации в artifactory
Конкретно в его случае описывается процесс в maven repository для публичной публикации. Основные настройки абсолютно идентичны: в каждом модуле, который нужно публиковать, вызываем gradle script файл из файла build.gradle модулей и создаем gradle.properties, где будет лежать конфигурационная информация для публикации. Нас интересует возможность публиковать в приватном artifactory
Нам необходимо добавить 2 папки для публикации в artifactory: одну для официального релиза и snapshot для тестовых сборок модулей.
Когда у нас наконец-то настроен конфигурационный файл gradle.properties, мы готовы сделать первую публикацию библиотек в artifactory. В тестовой сборке укажем SNAPSHOT в VERSION_NAME. Затем выполним команду:
Настройка CI окружения
Нам удалось вручную опубликовать модули в наш приватный artifactory. В завершениb осталось настроить CI окружение, чтобы мы могли встроить публикацию в наш процесс разработки.
Мы хотим, чтобы только CI мог публиковать в release artifactory, а для остальных добавим свободный доступ на чтение и запись в snapshot. Поэтому внесем изменения в корневом файле gradle.properties, который обычно лежит в
/.gradle/gradle.properties . Пропишем <%username%>и <%password%>для доступа при публикации в artifactory. Таким образом у нас будет настроен уровень доступа, без внесения изменений в .gitignore.
Добавляем trigger на ветку master, чтобы при merge у нас собралась сборка для публикации в release artifactory. В список задач сборок добавляем запуск тестов, если у нас в модуле они есть. Хорошо будет ещё настроить auto increment версии.
Используем модуль в продукте
Как только CI соберет сборку и зальет ее в artifactory, в проекте можно добавить зависимость этого модуля. Но погодите, нам же нужно добавить еще и url к нашему artifactory, ведь они недоступны в типичном repository как maven
Теперь мы можем использовать его в проекте.
С чем мы столкнулись
При подключении Kotlin в наши модули документация для Kotlin файлов не подтягивается. Оказалось, что для этого нужно добавить gradle задачу с Dokka.
Если несколько разработчиков указывали идентичные версии для библиотек при публикации, то, естественно, актуальной версией модели оказывалась последняя публикация. В процессе разработки модуля обязали указывать постфикс с идентификатором ticket из Jira. Получается что-то вроде 1.0.1-AAS-1-SNAPSHOT .
Что в итоге получилось
Со временем у нас возросло количество модулей. Мы держали каждый модуль в отдельном git repository. Множество git repository создает большое количество неудобств в процессе разработки, если модуль имеет зависимость от других модулей. В итоге получилось, что для выполнения одной задачи, необходимо было создавать PR в каждом git repository. Не совсем ясно, в каком порядке их нужно тестировать, не учитывая еще постоянное изменение PR, если в одном из PR внесли правки. Поэтому, использовать один git repository для всех модулей на практике оказалось удобнее всего.
Таких модулей у вас может быть множество. Если в том или ином проекте не требуется конкретный модуль, то мы легко можем убрать зависимость, что в итоге нам позволит не писать дублирующие коды в каждом из трех из наших проектов.
Такая модульная разработка внутренних компонентов бизнеса поможет нам повысить скорость доставки фичи до пользователей. В заключении стоит отметить важное преимущество модульной разработки — сборка apk файлов будет занимать намного меньше времени, так как gradle будет пересобирать только ту часть модуля, в которой произошло изменение.
Источник
How to Add a Library Project to 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. Some of you must have gone through this. Whenever you want to add some external library and you try to do that with maven(File > Project Structure > Dependencies) and try to add your dependencies there but when you hit Gradle sync, it fails. So now, without fixing this, you want to go for building your app then you will get the error: Error: A problem occurred configuring project ‘:app’. There are many external libraries available that make many specific tasks simple and easy with the APIs and Classes they provide. So including all those libraries in our project is really going to help you a lot. Many developers are often confused about how to add these libraries to their projects. This article is helpful for all such people.
In this article, we will see different ways to add library projects to our project. But before jumping to that let’s have a quick look at this: We can use Gradle, to add library projects with a single line code. Android Studio Project has a modular structure and we have a main module called “app”. There may be multiple modules in a Project. We can connect them together through Gradle, this connection is known as Dependency. Now Let’s get back to our main agenda.
Different Ways To Add Library Project to Android Studio
Method 1
Almost every well-known Android library is available in a Maven repository and its installation takes only one line of code in the app/build.gradle file:
Let’s add the external library to our project:
Step 1: Create a new project using Android Studio and name it anything you want (GFG in this example) and hit the finish button.
Step 2: The original project structure created by Android Studio looks like this:
Step 3: In the root directory (GFG/), create a new folder: /libs in which we’ll place our external libraries (this step is not required – only for keeping a cleaner project structure).
Step 4: Paste your library in the newly created /libs folder. For this example, we are using the PagerSlidingTabStrip library (you just need to download ZIP from GitHub, rename the library directory to “PagerSlidingTabStrip” and copy it). The new structure of our project should look like this:
Step 5: Edit settings.gradle by adding your library to include. If you use a custom path like I did, you have also to define the project directory for our library. A whole settings.gradle should look like below:
project(‘:PagerSlidingTabStrip’).projectDir = new File(‘libs/PagerSlidingTabStrip’)
Step 5.1: If you face “Default Configuration” error, then try this instead of step 5,
Step 6: In app/build.gradle add our library project as a dependency:
compile fileTree(dir: ‘libs’, include: [‘*.jar’])
Step 6.1: If you followed step 5.1, then follow this instead of 6,
compile fileTree(dir: ‘libs’, include: [‘*.jar’])
Step 7: If your library project doesn’t have build.gradle file you have to create manually.
Step 8: That’s all. Just click‚ synch the project with Gradle. Your library should be available for your project.
Method 2
Step 1: Follow to File > New Module
Click on “Import Existing Project“.
Step 2: Select the desired library and the desired module. Then click finish. Android Studio will import the library into your project and will sync Gradle files.
Step 3: In the next step you need to add the imported module to your project’s dependencies. Right-click on the app folder > Open Module settings
Step 4: Navigate to the dependencies tab > Click on the ‘+’ button -> click on Module Dependency. The library module will be then added to the project’s dependencies.
Method 3
Step 1: Navigate to File > Project Structure
Step 2: Then click on Modules.
To import the library using Gradle, you can have to add it to the dependencies section of your build.gradle (the module’s one).
Method 4
Just go to Project Structure > under Modules (see below images) just click the plus button and select Import Existing Project and import. Then sync your Gradle files. There are chances to face the error
Error: The SDK Build Tools revision (xx.x.x) is too low. Minimum required is yy.y.y
Then just open the build.gradle file in your library project directory and update the buildToolsVersion to the suggested one.
then try importing the module by clicking on File > Project Structure
Module > Import Module
After importing the library module, select your project module and add the dependency and then select the imported module.
Источник
Adding external library in Android studio
I want to add external library https://github.com/foursquare/foursquare-android-oauth to my Android application (I use Android Studio, the instructions provided by lib author for Eclipse didn’t work for Android Studio).
I’ve tried to do it with maven, so in File->Project Structure->Dependencies I’ve added com.foursquare:foursquare-android-nativeoauth-lib:1.0.0 but Gradle Sync fails:
When I try to build my app (without fixing above error becaus I don’t know how) I get:
Any other way to import this lib? I can simply copy-paste source code into my source or create JAR out of it?
BTW: if you run into problems see this question (I had this issue after importing): Manifest merger failed : uses-sdk:minSdkVersion 14
19 Answers 19
Try one of these approaches:
Approach 1)
1- Choose project view
2- Copy your JAR file in app -> lib folder
3- Right click on your JAR file and choose add as library
4- Check it in build.gradle
Approach 2)
1- File -> New -> New Module
2- Import .JAR/.AAR Package
3- Browse your JAR File
5- File -> Project Structure -> Dependencies
6- You should click on + button and then click on Module Dependency
7- You will see your library here
8- choose your library and click ok
9- Then, you will see that your library is added.
For first two approaches, you need a JAR file. You can search http://search.maven.org/ to find JAR files that are related to Android. For example, this is the search result for jdom in this link
Approach 3) Android is using http://jcenter.bintray.com/ as remote library. For example, this is the search result for jdom in the link.
To add a library in this approach, please follow these steps:
1- File -> Project Structure -> Dependencies
2- Click on + button and choose library dependency
3- find your library and select it, then click OK.
I hope it helps.
File > Project Structure > Dependencies Tab > Add module dependency ( scope = compile )
Where the module dependency is the project library Android folder.
To reference an external lib project without copy, just do this: — Insert this 2 lines on setting.gradle :
Insert this line on on dependencies part of build.gradle file:
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 you are using, and paste your library in External Libraries.
- 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.
Any other way to import this lib? I can simply copy-paste source code into my source or create JAR out of it?
Complete Steps for importing a library in Android Studio 1.1
- Goto File -> Import Module.
- Source Directory -> Browse the project path.
- Specify the Module Name
- Open build.gradle (Module:app) file
Add the following line with your module name
I had also faced this problem. Those time I followed some steps like:
File > New > Import module > select your library_project . Then include ‘library_project’ will be added in settings.gradle file.
File > Project Structure > App > Dependencies Tab > select library_project . If library_project not displaying then, Click on + button then select your library_project .
Clean and build your project. The following lines will be added in your app module build.gradle (hint: this is not the one where classpath is defined).
If these lines are not present, you must add them manually and clean and rebuild your project again ( Ctrl + F9 ).
A folder named library_project will be created in your app folder.
If any icon or task merging error is created, go to AndroidManifest file and add
Источник