- Creating and Publishing an Android Library
- Introduction
- 1. Creating an Android Library
- Step 1: Add a New Module
- Step 2: Create a Layout
- Step 3: Create a Java Class
- 2. Using the Library Locally
- 3. Publishing Your Library on Bintray
- Step 1: Add Necessary Plugins
- Step 2: Apply the Plugins
- Step 3: Specify POM Details
- Step 4: Generate a Sources JAR
- Step 5: Generate a Javadoc JAR
- Step 6: Include the Generated JAR files
- Step 7: Run Tasks
- Step 8: Configure the Bintray Plugin
- Step 9: Upload Files Using the Bintray Plugin
- 4. Using the Library From Bintray
- 5. Adding the Library to JCenter
- Conclusion
- Публикация Android библиотеки
- Регистрация на Sonatype JIRA и создание Issue
- Создаем Android библиотеку в Android Studio
- Генерации GPG ключа
- Настройка библиотеки для публикации:
- Публикация
- Первый
- Второй
- Заключение
Creating and Publishing an Android Library
Introduction
Our lives as Android developers would be a lot harder if not for all those third-party libraries out there that we love to include in our projects. In this tutorial, you will learn how to give back to the developer community by creating and publishing your own Android libraries, which people can effortlessly add and use in their projects.
1. Creating an Android Library
If your library is going to be composed of only Java classes, packaging it as a JAR and distributing it using a file host is perhaps the quickest and easiest way to share it. If you were to create it from the console, the following command would suffice:
This tutorial however, shows you how to work with more complex libraries that contain not just Java classes, but also various types of XML files and resources. Such libraries are created as Android library modules and are usually packaged as AAR files.
Let’s create a simple Android library that offers a custom View to developers who use it.
Step 1: Add a New Module
To begin, add a new Android module to your project by selecting New > New Module from the File menu. You will be shown the following screen, which offers lots of choices:
Select Android Library and press Next. In the form that follows, enter a name for your library and press Next. I’ll be calling this library mylittlelibrary.
In the last screen, select Add no Activity and press Finish.
Your project will now have two modules, one for the app and one for the library. Here’s what its structure looks like:
Step 2: Create a Layout
Create a new layout XML by right-clicking on the res folder of your library module and selecting New > XML > Layout XML File. Name it my_view.xml.
To keep this tutorial simple, we’ll be creating a custom View that has two TextView widgets inside a LinearLayout . After adding some text to the TextView widgets, the layout XML file should look like this:
Step 3: Create a Java Class
Create a new Java class and name it MyView.java. Make sure to put this file in the src directory of the library module–not the app module.
To make this class behave as a View , make it a subclass of the LinearLayout class. Android Studio will prompt you to add a few constructors to the class. After adding them, the new class should look like this:
As you can see, we now have two constructors. To avoid adding initialization code to each constructor, call a method named initialize from each constructor. Add the following code to each constructor:
In the initialize method, call inflate to associate the layout we created in the previous step with the class.
2. Using the Library Locally
Now that the library is ready, let’s make use of it in the app module of the same project in order to make sure that there are no issues. To do so, add it as a compile dependency in the build.gradle file of the app module:
Create a new Java class, MainActivity, inside the app module. Make it a subclass of the Activity class and override its onCreate method.
Inside the onCreate method, create an instance of the custom view using its constructor. Pass it to the setContentView method so that it fills all the screen space of the Activity :
Your Activity is now ready. After adding it to the app manifest, build your project and deploy your app to an Android device. You should be able to see the custom view when the app starts.
3. Publishing Your Library on Bintray
Bintray is a popular platform you can use to publish Android libraries. It is free and easy to use.
Start by creating an account on Bintray. After signing in to your account, you will see that you already own six repositories. You can either use one of them or create a new repository. For this tutorial, I will be using the repository called maven, which is a Maven repository.
Visit your profile page and click the Edit button. On the next page, click the API Key link to view your API key.
Make a note of the key, because you will be needing it to authenticate yourself when using the Bintray plugin.
Step 1: Add Necessary Plugins
To interact with Bintray in Android Studio, you should include the Bintray plugin in the dependencies of your project’s build.gradle file.
Because you will be uploading the library to a Maven repository, you should also add the Maven plugin as shown below.
Step 2: Apply the Plugins
Open the build.gradle file of your library module and add the following code to apply the plugins we added in the previous step.
Step 3: Specify POM Details
The Bintray plugin will look for a POM file when it uploads the library. Even though the Maven plugin generates it for you, you should specify the value of the groupId tag and the value of the version tag yourself. To do so, use the group and version variables in your gradle file.
If you are familiar with Maven and you are wondering why we didn’t specify the value of the artifactId tag, it is because the Maven plugin will, by default, use the name of your library as the artifactId .
Step 4: Generate a Sources JAR
To conform to the Maven standards, your library should also have a JAR file containing the library’s source files. To generate the JAR file, create a new Jar task, generateSourcesJar, and specify the location of the source files using the from function.
Step 5: Generate a Javadoc JAR
It is also recommended that your library has a JAR file containing its Javadocs. Because you currently don’t have any Javadocs, create a new Javadoc task, generateJavadocs, to generate them. Use the source variable to specify the location of the source files. You should also update the classpath variable so that the task can find classes that belong to the Android SDK. You can do this by adding the return value of the android.getBootClasspath method to it.
Next, to generate a JAR from the Javadocs, create a Jar task, generateJavadocsJar, and pass the destinationDir property of generateJavadocs to its from function. Your new task should look like this:
To make sure the generateJavadocsJar task only starts when the generateJavadocs task has completed, add the following code snippet, which uses the dependsOn method to order the tasks:
Step 6: Include the Generated JAR files
To include the source and Javadoc JAR files in the list of artifacts, which will be uploaded to the Maven repository, you should add the names of their tasks to a configuration called archives. To do so, use the following code snippet:
Step 7: Run Tasks
It is now time to run the tasks we created in the previous steps. Open the Gradle Projects window and search for a task named install.
Double-click it to run the tasks associated with the library module. Once it’s finished running, you will have everything you need to publish your library, a valid POM file, an AAR file, a sources JAR, and a Javadocs JAR.
Step 8: Configure the Bintray Plugin
To configure the plugin, you should use the bintray closure in your Gradle file. First, authenticate yourself using the user and key variables, corresponding to your Bintray username and API key respectively.
On Bintray, your library will reside inside a Bintray package. You should provide details about it using the intuitively named repo , name , licenses , and vcsUrl parameters of the pkg closure. If the package doesn’t exist, it will be created automatically for you.
When you upload files to Bintray, they will be associated with a version of the Bintray package. Therefore, pkg must contain a version closure whose name property is set to a unique name. Optionally, you can also provide a description, release date, and Git tag using the desc , released , and vcsTag parameters.
Finally, to specify the files that should be uploaded, set the value of the configuration parameter to archives.
This is a sample configuration:
Step 9: Upload Files Using the Bintray Plugin
Open the Gradle Projects window again and search for the bintrayUpload task. Double-click it to begin uploading the files.
Once the task completes, open a browser to visit your Bintray package’s details page. You will see a notification that says that you have four unpublished files. To publish these files, click the Publish link.
4. Using the Library From Bintray
Your library is now available as a Bintray package. Once you share the URL of your Maven repository, along with the group ID, artifact ID, and version number, any developer can access your library. For example, to use the library we created, developers would have to include the following code snippet:
Note that the developer has to explicitly include your repository in the list of repositories before adding the library as a compile dependency.
5. Adding the Library to JCenter
By default, Android Studio searches for libraries in a repository called JCenter. If you include your library in the JCenter repository, developers won’t have to add anything to their repositories list.
To add your library to JCenter, open a browser and visit your Bintray package’s details page. Click the button labeled Add to JCenter.
You will then be taken to a page that lets you compose a message. You can use the Comments field to optionally mention any details about the library.
Click the Send button to begin Bintray’s review process. Within a day or two, the folks at Bintray will link your library to the JCenter repository and you will be able to see the link to JCenter on your package’s details page.
Any developer can now use your library without changing the list of repositories .
Conclusion
In this tutorial, you learned how to create a simple Android library module and publish it to both your own Maven repository and to the JCenter repository. Along the way, you also learned how to create and execute different types of gradle tasks.
To learn more about Bintray, visit Bintray’s user manual.
Источник
Публикация Android библиотеки
Недавно у меня появилось желание попробовать создать свою собственную Android библиотеку и выложить ее на Maven Central репозиторий.
Это оказалось не так просто, как я думал. В интернете полно непонятных статей на эту тему, в которых легко запутаться.
Я решил поделиться процессом публикации моей библиотеки Awesome-Buttons.
Ну что ж, приступим.
Регистрация на Sonatype JIRA и создание Issue
Перейдите на сайт Sonatype JIRA и создайте себе аккаунт.
Теперь войдите в аккаунт и создайте новый Issue :
Заполните всю необходимую информацию.
Обратите внимание на Group Id . Обычно в качестве его указывается доменное имя в обратном порядке.
Если у вас есть свой сайт или сайт библиотеки, то вы можете использовать его доменное имя (например: ru.freeit256 ), но для этого нужно будет дополнительно прописать запись в вашем регистраторе домена (после создания Issue вы увидите информацию как это сделать).
Я использовал другой подход: указал свой Github в качестве Group Id
Также для того, чтобы использовать Github в качестве Group Id вам нужно создать пустой репозиторий с именем OSSRH-74088
Не забудьте отправить ваше Issue на проверку и дождаться статуса CLOSED
Создаем Android библиотеку в Android Studio
Сначала создайте любое пустое приложение с app модулем.
Затем вы можете либо добавить модуль Android библиотеки, либо изменить текущий модуль на библиотечный. Читайте об этом на официальном сайте
Генерации GPG ключа
Перед публикацией необходимо сгенерировать пару GPG ключей.
Для генерации ключей выполните следующую команду:
Основные параметры при создании ключей:
формат шифрования: RSA and RSA
размер: 4096 бит
срок годности ключа можно указать 0 (никогда не истечет)
имя, email и комментарий укажите свои
Чтобы посмотреть все сгенерированные ключи выполните команду:
Обратите внимание, последние 8 символов это ID ключа:
Для подписи библиотеки мы будем использовать приватный ключ, а чтобы пользователи смогли удостовериться, что библиотека принадлежит нам, мы должны выложить публичный ключ на общедоступный сервер, например keyserver.ubuntu.com:
Чтобы получить приватный ключ для подписи нужно выполнить:
Вуаля! Позже он нам понадобится.
Настройка библиотеки для публикации:
Добавляем плагин io.github.gradle-nexus в корневой файл build.gradle :
Далее нам нужно создать два скрипта для модуля и корня нашей библиотеки.
Создадим в корне проекта папку scripts , и добавим новый скрипт publish-module.gradle :
Также нам нужно добавить скрипт publish-root.gradle :
Теперь нам нужно добавить maven-publish плагин и некоторые константы в начало build.gradle файла нашего модуля:
И самый важный момент, файл local.properties :
Публикация
После основных настроек, зайдите на Nexus Repository Manager и войдите под учетными данными JIRA Sonatype.
Далее переходим во вкладку Staging Profiles и выбираем необходимый профиль.
Копируем sonatypeStagingProfileId из адреса сайта и указываем его в local.properties файле:
Переходим к публикации.
Далее у вас есть два варианта зарелизить либу: вручную через графический интерфейс или с помощью gradle задачи.
Первый
Зайдите на сайт Nexus Repository Manager , перейдите во вкладку Staging Repositories и выберите необходимый репозиторий.
Чтобы выпустить релиз библиотеки нужно воспользоваться двумя командами close и release .
Для отмены релиза юзайте drop
Второй
Выполните команду, которая сама закроет и зарелизит вашу либу:
Заключение
Вы уже убедились, что процесс публикации Andorid либы весьма затратный и рутинный.
Я постарался изложить только основные моменты. Возможно у вас возникнут какие-либо ошибки, которые вам придется самим решать ну и конечно же гуглить!
Такова жизнь прогера: постоянно гуглить. 🙂
Надеюсь, что статья оказалась вам полезной.
Желаю всем хорошего кода и побольше успешных релизов! 🙂
Источник