Android или android support

Android Support Library: немного о версионности

Mar 11, 2018 · 4 min read

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

Зачем мы это используем

При разработке приложений, мы часто хотим видеть одинаковую работу нашего кода на разных версиях устройств. Вместо того, чтобы писать код поддержки для ранних версий Андроид, нам достаточно взять готовую реализацию из Support Library и заняться более важными задачами (таски же должен кто-то закрывать).

Однако т а к было ранее, ведь сейчас, библиотека поддержки это куда больше, чем куча if else с проверкой версионности. Она содержит в себе такие полезные view как:

  • RecyclerView — отличная альтернатива устаревшему ListView
  • ViewPager — для реализации таб-ориентированной навигации или простого слайдинга
  • DrawerLayout — позволяющий быстро и просто добавить боковое меню
  • CardView — для разнородного контента

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

Как строится нейминг библиотек

В документации можно видеть список всех доступных для подключения библиотек с их кратким описанием.

Большинство библиотек поддержки имеет префикс, который ПО-СЛУХАМ говорит о минимальной версии андроид, необходимой для её работы.

Помимо упомянутых ранее виджетов, библиотека поддержки предоставляет нам улучшенный GridLayout , библиотеку Palette для работы с цветами, а также Preference Library для реализации экрана настроек (которой никто не пользуется, кек)

Подключаются они все примерно одинаково:

за исключением того, что у библиотек v4 отсутствует префикс)) Добро пожаловать в мир андроид разработки, здесь довольно часто в порядке вещей делать, казалось бы, одну и ту же вещь по разному. Даже гугл не стремается, нам то уж чего.

v4 уже считается довольно устаревшей и по дефолту студия генерирует нам семплы именно с v7 , чего и я советую вам придерживаться.

com.android.support:appcompat-v7 тянет за собой целый ворох различных зависимостей (даже архитектурных. а вы тут всё “какааая архитектура в ондроид”)

С одной этой подключенной библиотекой v7 , проект уже использует примерно 30% от всего доступного места (если считать по количеству методов). Ради справедливости стоит отметить, что здесь подключен и Котлин являющийся де-юро (но пока далеко не де-факто) стандартом разработки под Андроид.

и некоторые из этих библиотек мне не нужны, к примеру фрагменты и все её дочерние 13 зависимостей. Вместо них я использую обычные view (на примере Conductor) и кастомный роутинг (на примере Cicreone). Давайте посмотрим, сколько места нам удасться сэкономить если мы их отключим:

Согласно dex-count наши фрагменты занимают 1740 методов.

Отключаем их простой командой из gradle

пытемся собрать и огосподи BUILD FAILED ! Что же могло пойти не так?

Давайте глянем на логи и разберемся:

Это попросту значит, что в пакете фрагментов, лежит реализация FragmentActivity , которая используется в пакете AppCompatActivity , которую уже используем мы для своих активностей.

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

Помимо этого, была замечена вот какая штука

Обратившись к документации мы видим очень явную и понятную строчку, прочитав которую не было бы этой статьи, отнявшей у вас время:

Note: The minimum SDK version for all support library packages is at least API level 14. Some packages require a higher API level, as noted below.

Т.е. какую бы версию библиотек мы не подключили, минимальный API Level будет = 14 или выше.

А это значит, что префикс в названии библиотек не говорит по сути абсолютно ни о чем, ведь использовать их мы можем лишь с минимальной api = 14.

Читайте также:  Кодек для мх плеера для андроид

Проверяем и убеждаемся

Расследование можно считать закрытым. Спасибо за внимание!

Источник

Migrating to AndroidX: tips, tricks, and guidance

Take advantage of the latest Jetpack has to offer.

Jetpack is a set of libraries, tools, and guidance to help you write high-quality apps more easily. Jetpack makes coding easier through best practices, limiting boilerplate code, and simplifying complex tasks. All with the goal of enabling you to focus on the code that you really care about.

AndroidX is the package name for all the libraries within Jetpack. Think of AndroidX as the open-source project used to develop, test, version, and release Jetpack libraries.

Back at I/O 2018, we announced that Support Library would be refactored into the AndroidX namespace, which was completed with Support Library 28 and the announcement of AndroidX 1.0.

Why migrate?

The time is right now to migrate from using the Android Support Library to AndroidX. There are four reasons behind this:

  1. The Android Support Library has reached the end of its life. 28.0 was the last release of the Android Support namespace and the namespace is no longer maintained. So, if you want bug fixes or new features that would have previously gone into the Support Library, you need to migrate to AndroidX.
  2. Better package management. With AndroidX, you get standardized and independent versioning, as well as better standardized naming and more frequent releases.
  3. Other libraries have migrated to use the AndroidX namespace libraries, including Google Play services, Firebase, Butterknife, Mockito 2, and SQLDelight among others.
  4. All new Jetpack libraries will be released in AndroidX namespace. So, for example, to take advantage of Jetpack Compose or CameraX, you need to migrate to the AndroidX namespace.

Preparing to migrate

Before you start to migrate to AndroidX you should:

  • back up your project. If you’re using source control tools, it is still recommended that you make a backup, because migration will change many of the files in your project.
  • create a new branch on which to make the migration changes.
  • if possible, suspend or minimize development (at least don’t try to do refactoring or pull in new features) during the migration, as this will help reduce the number of merge conflicts that could happen.

Migrate

Throughout the migration steps focus on addressing errors, getting your app to compile, and passing all tests.

Step 1: Update to Support Library version 28

Migrating directly to AndroidX from an older version of the Support Library, say 26 or 27, isn’t recommended: not only would you need to address the namespace changes, you would also need to address the API changes between the older version and AndroidX.

It is, therefore, recommended that you update to version 28, address all of the API changes, and ensure your app compiles with version 28.

Support Library version 28 and AndroidX 1.0 are binary equivalent, meaning that only the package name changes between those two versions: all the APIs are the same. This means that you should have very little to fix when migrating from 28 to AndroidX.

Step 2: Enable Jetifier

Jetifier helps migrate third-party dependencies to use AndroidX. Jetifier will change the byte code of those dependencies to make them compatible with projects using AndroidX. However, Jetifier won’t change your source code or migrate your generated code.

To enable Jetifier in your app, add the following to your gradle.properties files:

Now, when code auto-completion import libraries, you’ll import the AndroidX version of that library instead of the old Support Library version.

Step 3. Update dependencies

Before starting the migration, you should update each third-party library — such as Butterknife, Glide, Mockito 2, and SqlDelight — to the most recent version of the library. Not doing so could result in unexplained compilation errors.

Читайте также:  Java runtime apps android

If you’re using a code generation library, Jetifier won’t modify these. So you will need to check that the code generation library is compatible with AndroidX.

If you consider skipping steps 2 and 3 here are some of the errors you could encounter:

  • the third-party code you’re using is not compatible with AndroidX. In this case, a stack trace similar to the one below will show you that it’s trying to pull in the old version of the Support Library:
  • if you have a project that’s partially migrated, you might get a duplicate class error, where it’s trying to pull in the same code from both the Support Library and AndroidX. The stack trace will show you something like this:

Step 4: Update your source code

You have 3 options to update your source code to use AndroidX:

  • Android Studio
  • manual update
  • Bash script

If you use Android Studio 3.2 stable or above, you can update your source code using the Migrate to AndroidX option on the Refactor menu. This is the recommended way as Android Studio can examine your source code to make correct decisions when refactoring.

If you don’t use Android Studio or employ a more sophisticated app architecture that the Migrate to AndroidX option doesn’t cover, you should instead leverage the class mapping csv file to implement a find and replace bash script. This script should find all source code instances of the android.support classes and then replace them with their AndroidX equivalent.

More concretely, the script should take the CSV file that provides the class mapping and then run a grep command followed by a sed command to replace the package names. However, because this is a brute force approach to migration, this basic find and replace may not sufficiently or correctly complete the migration.

Additionally, the update can also be done manually.

If you decide to take the manual approach, visit the Migrate to AndroidX page, where you can find an artifact mapping that details the Support Library packages and their corresponding class mapping is AndroidX. You can also download the CSV file from this page.

And that’s it, you should now have a project that compiles and uses AndroidX.

Those pesky exceptions

While the tools and processes we’ve discussed here should guide most apps smoothly through the migration, we’ve found that there are some cases where you may need to make changes manually.

Version configuration files

You will need to manually reapply variables that define library versions. To illustrate, your build.gradle file might look like this prior to migration:

Then, after running the migration tool you end up with this:

DrawerLayout and RecyclerView are using the AndroidX packages, but the version numbers are now inline. Also, the versions variable numbers have not been changed. So you’ll need to do a manual update to this:

ProGuard and build scripts

The migration tool doesn’t automate updates to ProGuard and any associated built scripts. So, if you’re using these and have package names in them, you’ll need to edit these manually.

Get the latest stable version

The migration tool pulls in the most recent release of the AndroidX libraries. As a result, you may end up with an alpha version of some libraries rather than the stable version. For example, the support library version before migration might be:

And after migration, you would be using the alpha version of the corresponding AndroidX library:

So, if you prefer to use the stable version of the library, you’ll need to manually update the version:

More help and resources

You can find more information about this process, the tools, and issues you may encounter on the developer.android.com Migrating to AndroidX page. The page includes an overview of the AndroidX project, a migration guide, and the mapping table of the old Support Library to the new stable and alpha AndroidX versions with the CSV files you need to script your migration.

Elsewhere, there is also an article detailing the migration to AndroidX in the Plaid example project.

And finally, there is an issue tracker where you see the migration tool issues that the team is working on. You can, of course, report any issues you find with the migration tool here using the button at the top left of the page.

Читайте также:  Программирование для чайников android studio

Final thoughts

If you haven’t upgraded to AndroidX, this is a great time to do so and take advantage of the streamlined development that the Jetpack libraries offer your apps. By following the guidance in this article you should find that, in most cases, migration is a straightforward and easy thing to do.

Do you have thoughts on AndroidX? Let us know in the comments below or tweet using #AndroidStudio and we’ll reply from @AndroidDev, where we regularly share news and tips on how to be successful on Android.

Источник

Android X: знакомимся с изменениями в новой библиотеке поддержки

Авторизуйтесь

Android X: знакомимся с изменениями в новой библиотеке поддержки

Google перенесла разработку проекта AndroidX на AOSP. AndroidX — новая библиотека поддержки, которая добавляет новые функции и изменяет некоторые старые. Поговорим об этих изменениях.

Пространства имён android.* против androidx.*

Android-приложения зависят от двух типов классов:

  • Классы вроде PackageManager , которые идут в комплекте с операционной системой и могут иметь разные API и поведение на разных версиях Android;
  • Классы вроде AppCompatActivity или ViewModel , которые отделены от операционной системы и включаются в ваш apk. Эти библиотеки пишутся для предоставления API, поведение которого будет неизменным на как можно большем количестве версий Android.

Зачастую библиотеки, не идущие в комплекте, будут лучшим выбором, так как они предоставляют API для многих версий Android. Теперь все такие библиотеки, включая оные из Support Library и Architecture Components, будут включены в пространство имён androidx.* , чтобы вы понимали, какие зависимости нужно подключать.

Изменение в именовании пакетов и артефактов Maven

Также была переработана структура пакетов, чтобы поощрить создание небольших, более сфокусированных библиотек, которые уменьшат давление на приложения и тесты, не использующие ProGuard и Multidex. Были обновлены groupId и artifactId Maven, чтобы лучше отражать содержимое библиотеки. Кроме того, теперь к пакетам библиотеки добавляется префикс в виде их groupId , чтобы создать очевидную связь между используемым классом и артефактом Maven, из которого он берётся.

Сейчас вы можете ожидать следующее сопоставление старых пакетов с новыми:

android.support.** → androidx.@
android.databinding.** → androidx.databinding.@
android.design.** → com.google.android.material.@
android.support.test.** → (в будущем релизе) androidx.test.@

Так как библиотеки Architecture Components теперь включены в пакет AndroidX, их имена были упрощены, чтобы отразить их интеграцию с основными библиотеками. Примеры изменений:

android.arch.** → androidx.@
android.arch.persistence.room.** → androidx.room.@
android.arch.persistence.** → androidx.sqlite.@

Кроме того, поскольку в версии 28.0.0-alpha1 Material Components станут заменой Design Library, был обновлён пакет дизайна, чтобы отразить его новое направление.

Для получения полного списка сопоставлений от 28.0.0-alpha1 ( android.support ) к 1.0.0-alpha1 ( androidx ) посетите эту страницу. Учтите, что в течение альфа-стадии в этот список могут быть внесены небольшие изменения.

Строгое версионирование для каждой библиотеки

Начиная с рефакторинга AndroidX, версии библиотек были сброшены с 28.0.0 до 1.0.0. Будущие обновления будут версионироваться отдельно для каждой библиотеки, следуя строгим правилам, согласно которым основная версия будет указывать на бинарную совместимость. Это значит, например, что вы можете добавить и использовать новую функцию в RecyclerView без обновления всех остальных библиотек, используемых вашим приложением. Также это значит, что библиотеки, зависящие от androidx , могут предоставить гарантии приемлемой совместимости с будущими релизами AndroidX — так, зависимость от версии 1.5.0 может работать с версией 1.7.0, но, скорее всего, не будет работать с версией 2.0.0.

Миграция с 28.0.0-alpha1

Переход приложения от зависимостей android.support к зависимостям androidx проходит в два основных этапа: рефакторинг исходного кода и перевод зависимостей.

Рефакторинг исходного кода обновляет Java-код, XML-ресурсы и конфигурацию Gradle таким образом, чтобы ссылаться на отрефакторенные классы и артефакты Maven. Эта функция доступна в Android Studio Canary 14 для приложений, ориентированных на Android P.

17–19 декабря, Онлайн, Беcплатно

Если вы зависите от библиотеки, которая ссылается на более старую версию Support Library, Android Studio обновит эту библиотеку с помощью перевода зависимостей так, чтобы она ссылалась на androidx . Перевод зависимостей автоматически применяется Android Gradle Plugin 3.2.0-alpha14, который переписывает байт-код и ресурсы зависимостей JAR и AAR (а также транзитивных зависимостей) таким образом, чтобы они ссылались на новые androidx классы и артефакты. Также будет доступен отдельный инструмент для перевода в формате JAR.

Источник

Оцените статью