- Создание Android-проектов с использованием Maven
- Что вы создадите
- Что вам потребуется
- Как проходить этот урок
- Настройка проекта
- Создание структуры каталогов
- Создание Android манифеста
- Установка Maven
- Настройка простой Maven сборки
- Сборка Android кода
- Описание записимостей
- Пересборка Android кода с зависимостями
- Building Android Apps with Apache Maven — Tutorial
- 1. Gradle for building Android applications
- 1.1. Using Gradle for Android apps
- 1.2. Conversion process from source code to Android application
- 1.3. Using Gradle on the command line
- 1.4. Removing unused resources and Java classes via resource shrinking
- 1.5. Defining dependencies and keeping the version external
- 2. Building Android applications with Maven
- 3. Tutorial: Building Android Applications with Maven
- 4. More information
- How to: make a Maven build script for Android
- But…why?
- Installing all the stuff
- A new project
- Running Maven from the command-line
- Conclusion
Создание Android-проектов с использованием Maven
Этот урок освещает создание простого Android проекта с Maven.
Что вы создадите
Вы создадите Android приложение, которое отображает время дня, а потом соберете его Maven’ом.
Что вам потребуется
- Примерно 15 минут свободного времени
- Любимый текстовый редактор или IDE
- JDK 6 и выше
- Android SDK
- Android устройство или эмулятор
Как проходить этот урок
Как и большинство уроков по Spring, вы можете начать с нуля и выполнять каждый шаг, либо пропустить базовые шаги, которые вам уже знакомы. В любом случае, вы в конечном итоге получите рабочий код.
Чтобы начать с нуля, перейдите в Настройка проекта.
Чтобы пропустить базовые шаги, выполните следующее:
- Загрузите и распакуйте архив с кодом этого урока, либо кнонируйте из репозитория с помощью Git: git clone https://github.com/spring-guides/gs-maven-android.git
- Перейдите в каталог gs-maven-android/initial
- Забегая вперед, установите Maven
Когда вы закончите, можете сравнить получившийся результат с образцом в gs-maven-android/complete .
Настройка проекта
Для начала, вам необходимо настроить Android проект для сборки Maven. Т.к. основное внимание данного урока уделено Maven, сделайте проект настолько простым, насколько это возможно. Если вы впервые работаете с Android проектами, установите и настройте ADT.
Создание структуры каталогов
В выбранном вами каталоге проекта создайте следующую структуру каталогов; к примеру, командой mkdir -p src/main/java/org/hello для *nix систем:
Создание Android манифеста
Android Manifest содержит всю информацию, необходимую для запуска Android приложения и оно не будет собираться без него.
Добавьте текстовую строку. Текстовые строки могут ссылаться на файлы приложения или другие источники.
Теперь определите визуальную структуру пользовательского интерфейса вашего приложения.
В директории src/main/java/org/hello вы можете создать любой Java класс, какой захотите. В соответствии с задачей урока, создайте следующий класс:
Установка Maven
Теперь у вас есть проект, который вы можете собрать с помощью Maven. Следующим шагом будет установка Maven.
Загрузите Maven как zip-файл с http://maven.apache.org/download.cgi. Достаточно только бинарники, поэтому смотрите ссылку на apache-maven-
Загрузите и распакуйте файл, затем добавьте bin каталог в переменную окружения PATH.
Чтобы протестировать устаноку Maven, запустите mvn из командной строки:
Если все хорошо, то вы должны увидеть информацию об установке, похожую на эту:
Теперь у вас есть установленный Maven.
Настройка простой Maven сборки
Теперь, когда Maven установлен, вам необходимо создать определение Maven проекта через XML-файл pom.xml. Помимо всего остального, этот файл содержит имя проекта, версию и зависимости, которые он имеет от внешних библиотек.
Создайте файл с названием pom.xml в корне проекта и поместите в него следующее содержимое:
Это простейший pom.xml файл, который необходим для сборки Android проекта. Он состоит из следующих настроек проекта:
— Как проект будет собран, в данном случае как Android APK
Секция dependencies определяет список зависимостей проекта. В частности, она определяет единственную зависимость от Android библиотеки. В элементе dependency зависимость определяется деревом дочерних элементов:
В данном случае элемент имеет значение provided . Зависимости этого типа необходимы для компиляции кода проекта, но будут доступны и во время выполнения кода. К примеру, Android API всегда доступен, когда Android приложение запущено.
Секция определяет дополнительную конфигурацию для сборки приложения. В этой секции есть секция
, которая содержит список плагинов, которые добавляют функциональность процессу сборки. Здесь определена конфигурация для Android Maven Plugin. Для этой зависимости также имеются элементы , и . Плагин также содержит следующие элементы:
- — Конфигурация плагина. Здесь вы определяете, с каким Android Platform SDK будет собираться проект
- — Комбинация указания значений true и apk для
передает управление [Android Maven Plugin] в процессе сборки.
На текущий момент вы определили пока минимальный Maven проект.
Сборка Android кода
Сейчас Maven готов к сборке. Вы можете выполнить выполнить несколько задач сборки уже сейчас, включая компиляцию кода проекта, создание библиотеки пакета(JAR файл) и установить библиотеку в локальный репозиторий Maven зависимостей.
Эта команда запускает Maven, говоря ему выполнить задачу compile. Когда он завершит её, вы должны найти скомпилированные .class файлы в каталоге target/classes.
Т.к. вы вряд ли захотите работать или распостранять .class файлы непосредственно, взамен этого возможно запустить package задачу:
Эта задача компилирует ваш Java код, запускает тесты и упаковывает код в JAR файл каталоге target. Имя JAR файла состоит из значений и проекта. К примеру, исходя из содержимого pom.xml файла, отображенного ранее, JAR файл будет называться gs-maven-android-0.1.0.jar.
Т.к. вы установили значение элемента
в «apk», результатом будет АРК файл в target каталоге в дополнение к JAR файлу. Этот АРК файл является упакованным Android приложением, готовым к развертыванию на устройстве или эмуляторе.
Android Maven плагин предоставляет несколько Maven задач, которые вы можете использовать в различных фазах процесса сборки или взаимодействия с устройством и эмулятором. Список доступных задач вы можете увидеть, выполнив команду:
Описание записимостей
Простой Hello World пример полностью самодостаточен и не зависит от каких-либо дополнительных библиотек. Однако, большинство приложений, зависят от внешних библиотек, предоставляющих некоторую функциональность.
К примеру, предположим, что вы хотите, чтобы приложение отображало текущие дату и время. Несмотря на то, что вы фактически можете использовать дату и время из нативных Java библиотек, возможно использовать более интересные для этого вещи, которые предоставляют Joda Time библиотеки.
Для этого, измените HelloActivity.java как показано ниже:
В этом примере используемый Joda Time LocalTime класс возвращает и отображает текущее время.
Если вы запустите mvn package сейчас, то сборка завершится с ошибкой, потому что вы не описали Joda Time как компилируемую зависимость в сборке. Для исправления этой ошибки, просто добавьте следующие строки в секцию файла pom.xml.
Пересборка Android кода с зависимостями
Теперь, если вы выполните mvn compile или mvn package , то Maven должен разрешить Joda Time зависимость из Maven Central репозитория и успешно собрать проект.
Ниже приведена полная версия pom.xml файла:
Поздравляем! Вы только что создали простой, но эффективный Maven проект с целью сборки Android проектов.
Источник
Building Android Apps with Apache Maven — Tutorial
Android Maven. This tutorial describes how to build Android applications with Apache Maven and the «android-maven-plugin».
1. Gradle for building Android applications
1.1. Using Gradle for Android apps
By default, Android projects are handled by the Gradle build system. If you create a new project in Android studio, the Gradle build scripts are automatically created. Android studio provides the Gradle runtime, hence no additional installation is required.
If you press the run button in Android Studio, it triggers the corresponding Gradle task and starts the application.
You can also run Gradle via the command line. To avoid unnecessary local installation, Gradle provides a wrapper script which allows you to run Gradle without any local installation.
You find the available versions of the Android Gradle plug-in under the following URL: https://jcenter.bintray.com/com/android/tools/build/gradle/
1.2. Conversion process from source code to Android application
The Java source files are converted to Java class files by the Java compiler. The Android SDK contains a tool called dx which converts Java class files into a .dex (Dalvik Executable) file. All class files of the application are placed in this .dex file. During this conversion process redundant information in the class files are optimized in the .dex file. For example, if the same String is found in different class files, the .dex file contains only one reference of this String .
These .dex files are therefore much smaller in size than the corresponding class files.
The .dex file and other resources, e.g., the images and XML files, are packed into an .apk (Android Package) file. The program aapt (Android Asset Packaging Tool) performs this step.
The resulting .apk file contains all necessary data to run the Android application and can be deployed to an Android device via the adb tool.
As of Android 5.0 the Android RunTime (ART) is used as runtime for all Android applications. ART uses a combination of Ahead Of Time and _Just In Time _ compilation. During the installation of an application on an Android device, the application code is translated into machine code.
The dex2oat tool takes the .dex file created by the Android tool chain and compiles that into an Executable and Linkable Format (ELF file). This file contains the dex code, compiled native code and meta-data. Keeping the .dex code allows that existing tools still work.
1.3. Using Gradle on the command line
The Gradle build system is designed to support complex scenarios in creating Android applications:
Multi-distribution: the same application must be customized for several clients or companies
Multi-apk: supporting the creation of multiple apk for different device types while reusing parts of the code
You can start your Gradle build via the command line. Here is an overview of the important Android Gradle tasks:
Command | Description |
---|---|
If you put the ext closure into the root build file, you can access its properties for example with ‘$rootProject.ext.junitVersion’. |
2. Building Android applications with Maven
The android-maven-plugin plug-in allows to build Android applications via Maven.
The webpage of this maven plug-in is located under: http://code.google.com/p/maven-android-plugin/ — Android-Maven Plug-in.
The Eclipse support of this plug-in is provided by the https://github.com/rgladwell/m2e-android — m2e project.
You only have to install Maven, write a correct pom.xml file and issue the commands to Maven to build, install and run your application.
The following will build your Android application via Maven.
This will create the application and places the .apk file in the target_ folder.
If you want to install the application via Maven on your Android device, you can use the following command.
If more than one device is available you can specify the relevant device in your pom.xml. Maven can also start and stop an Android virtual device automatically for you.
You can also start the application via Maven.
3. Tutorial: Building Android Applications with Maven
Create a new Android project called «de.vogella.android.build.firstmaven». The actual content of the repository is not important as we are only using this project to create a working build for Maven.
Create the following «pom.xml» file in your directory. Make sure that artifactId is set to your project name.
Switch to the command line and enter the following command:
4. More information
For more information see the complete Maven Android Guide from Sonatype:
Another quick starting guide is available on the android-maven-plugin project side:
Источник
How to: make a Maven build script for Android
September 16, 2012 3 minute read
I’ve written before about writing Android apps in Scala. Sometimes, though, Scala isn’t the answer, and you need to fall back on Java. That doesn’t necessarily mean you should also fall all the way back to Ant, though. This post is about creating a Maven build script for an Android app written in Java.
But…why?
In order to have a repeatable build, one that you could also run from a build server, you need a build script. Building and deploying from Eclipse might work fine if you’re a single person on a fire-and-forget project, but once you’re working with more than one person, or if you need to go back to a project you were doing a few months ago on a different version of Eclipse, you’re going to want to have a proper build script.
But Android already provides an Ant script, why would you want to use Maven if you need to install and configure lots of stuff to it? Isn’t Ant good enough?
Yeah, for a simple project, it probably is. But once your project gets more complicated, it’s nice when Maven has your back. Especially if you have to manage dependencies (other than Android), Maven can be a life-saver. And this is coming from someone who has no particular love for Maven. Between Ant and Maven, Maven is, quite simply, the lesser of two evils.
Installing all the stuff
First, download Eclipse. I recommend Eclise Juno (4.2). If you use Indigo (3.7), you will need to install the M2Eclipse plugin as well.
NOTE: are you running Linux on a 64 bit machine? Then do this first: sudo apt-get install ia32-libs It’s somewhere in Google’s documentation that you should do this, but it’s easy to miss and it took me some googling before I figured this out.
Next, install the Android ADT plugin. It comes with a nice wizard that downloads the SDK for the platform(s) of your choice and helps you set up an emulator.
Then, you need to install m2e-android. The install process is described on m2e-android’s website. Don’t have the Eclipse Marketplace installed? You can get it here.
A new project
Instead of creating a new Android Project, you should create a new Maven Project. The first time, you need to configure a Maven archetype. Don’t worry, this is super easy and the m2e-android website explains very well how to do it. It also explains how you can convert an existing Android project to Maven.
Congratulations! You’re good to go now.
Running Maven from the command-line
As I explained above, you might want to run your build on a build server. If you do, or even if you simply want to run your build from the command-line, you need to do a couple extra things.
First, you need to install Maven 3, since it won’t work with Maven 2. Also, make sure it’s on your PATH . Check this by running mvn -version ; it should say something like Apache Maven 3.0.4 ; not Apache Maven 2.2.1 (or some other version in the 2.x.y range).
And while you’re fiddling with environment variables, make sure that the ANDROID_HOME variable is set correctly as well. If you don’t know where your SDK is located, open Eclipse’s Preferences screen from the Window menu. You can find the SDK location in the Android tab.
To make things easier (even though, technically, it’s cheating), you can add your ADV to the Maven pom file. That way, Maven will automatically deploy your app to the given ADV, so you don’t have to provide it manually every time you run Maven. In the
section, find the android-maven-plugin . It has a section, where you can add the following lines:
Obviously, you need to replace my_adv_name with the name of an ADV that you have actually configured.
Once all this is out of the way, you can finally run Maven from the command-line! Useful commands include:
Be sure to run mvn clean install at least once before running mvn android:deploy or mvn android:run , or else you might start to see weird error messages about “trying to figure out package name from inside apk file”.
Conclusion
That’s it! Good luck! And if I missed something, please let me know. This kind of instructions tends to change over time, so while this works at the time of writing (which is September 16th, 2012), it might no longer work at the time of reading (which is, well, now).
Источник