Android app with maven

Создание 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.zip или apache-maven--bin.tar.gz.

Загрузите и распакуйте файл, затем добавьте 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:

Table 1. Android Gradle build targets

build project, runs both the assemble and check task

./gradlew clean build

build project complete from scratch

./gradlew clean build

build project complete from scratch

Run the instrumentation tests

To see all available tasks, use the gradlew wrapper command.

This command creates in the build folder the output of the Gradle build. By default, the Gradle build creates two .apk files in the build/outputs/apk folder.

To build and start your unit tests on the JVM use the following command.

To build and start your instrumented tests on your Android device use the following command.

1.4. Removing unused resources and Java classes via resource shrinking

The Gradle build system for Android supports resource shrinking at build time. This automatically removes resources that are unused from the packaged application. In addition to that, this also removes unnecessary resources from libraries you are depending on. This can hugely reduce the size of your application.

To enable resource shrinking, update your build file similar to the following snippet.

1.5. Defining dependencies and keeping the version external

A good practice is to define the version of your library dependencies outside the dependencies closure for better maintenance.

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:

Источник

Android local libraries with Maven

Jan 20, 2018 · 5 min read

Intro

Have you ever created Android library? You know, when you are working on specific functionality in some project and get enlightenment “hey, I could use this in some other project!”. No? Well… you should — at least sometimes 🙂 I don’t mean creating new ultimate architecture framework every week (we are not JavaScript developers after all), but writing simple tools that you know how to use and that will make your work easer on future projects. I recommend trying this, getting stars on GitHub and showing friends your library at AndroidArsenal is cool.

Here is some random tutorial on how to put your lib on JitPack: How to JitPack your lib. When it’s there, you can use it like every other dependency in project.

Why even

Anyway, this text is not about just creating libraries and putting them online. You may not want to make your libs opensource or store them externally, but still benefit from having great tools you’ve made. Solution is local Maven repository. It also gives you a very easy way to work on your library and test it immediately on project you need this library for. Without this, every time you want to fix or add something to your lib, you need to update it’s version, make release on Github, send it to JitPack, wait until it builds, hope it won’t fail, update version of lib in your project, and then if everything goes well check if it does it’s work. Of course your lib should contain sample application that shows usage of all library features, so you can test if it’s working without this whole release process, but sometimes it’s not enough and you need to test on real project.

Entry info

  • you dont need to install anything in your system, it’s all in Gradle plugin
  • no need to use command line
  • no need to modify your project, just build.gradle file
  • you don’t have to know where are your local libs stored, but its good to know:
  • each local release overrides previous one with same version number, so there is no need to update version each time (like for JitPack or other remote Maven repository)
  • you may have many local versions of your library, versioning works in the same way. You can even develop separate versions of your lib that are used in different projects, because of different minSdkVersion etc.

Sample code in Kotlin is available on GitHub. There are 2 projects in repo: app that contains application using locally published libraries from project library . Library project has sample application and 2 library modules: firstlib and secondlib . They are dead simple and contain just custom button class that overrides initial background color.

How to

Sounds too good to be true? Don’t worry, there is no catch.

Library

In your library module build.gradle you have to add (usually on top of file):

If you publishing your lib to JitPack, there is a chance you have below variables set. If not, just add below lines before android block.

Now is the only tricky part. Following code should be added at the bottom of lib module build.gradle , after any blocks you already have there.

Typical case

If your lib is single module, or you have many library modules in single project but without mutual dependencies:

Not-so-typical case

If your library project contains many modules that are independent libs and one that is collection of them — it might sound stupid but sometimes it’s useful. You can use it also for single module, but it’s just an overkill :

Protip

You can create file with publishing code and apply it in each module instead of copy-paste whole thing. You can see it used in Github project in module secondLib of library project. There is a file publish_local.gradle in library project root folder that contains publishing code. In library module you can now just add

Just remember to set variables artifactId and groupId , they are individual for each module.

Publish your lib

All you need to do now is run task: publishToMavenLocal .

So what is it for actually? You are telling maven-publish to release your library module to local Maven repository with name you’ve set in artifactId and package set in groupId . For multi-module project, it just iterates over modules and if they have publishing code they are also published to local repository.

Project

All you have to do in project you want to use locally published library, is add in project root build.gradle file mavenLocal() in repository list, so it looks like that:

How it works: Gradle while building your project will look for dependencies first in local Maven repository, then if it won’t find requested dependency it will try JCenter etc. So if you are using CI, your library should be released on source that CI have access to, like remote repository (private Nexus server, JitPack). I highly recommend using local repository only for development and testing your lib, and then publishing it somewhere when you are sure your work is done.

Outro

This approach to library development saved me tons of useless work and waiting for publishing on remote repository. I hope with this tutorial I can save some of your time. Or maybe you’ve figure it out in better way? 🙂

This article was originally posted on my own site .

Источник

Читайте также:  Android keystore key password
Оцените статью