Настройка flavors android studio

Как пользоваться Product Flavors и Build Variants для создания нескольких версий приложения

Product flavors — незаменимая gradle-фича, полезная при создании нескольких версий одного Android-приложения (имею ввиду, например, версии demo/full/pro, а также вариации под различные устройства). Достаточно добавить несколько строк кода в раздел android <. >файла build.gradle :

В productFlavors могут находиться все те же правила, что и в элементе defaultConfig . В данном случае я переопределил applicationId , чтобы в Google Play это было отдельным приложением, и versionName , чтобы у пользователя отображалась соответствующая версия. Кстати, из defaultConfig эти дублирующие правила можно будет убрать.

После правки обновите проект (нажмите Sync Now, либо Refresh Gradle projects). Теперь можно добавлять классы и ресурсы специально для каждой из версий приложения.

Например, чтобы добавить ресурс, нужно кликнуть ПКМ по названию модуля и выбрать New > Android resource file. Далее можно будет указать для какой версии приложения нужен данный ресурс:

Таким образом можно легко дать приложению информацию о том, в каком режиме оно запущено, debug или release. Достаточно иметь 2 value-ресурса, один в main , другой, скажем, в debug , и в каждый из них добавить строчку с нужным значением, которое затем проверять при запуске приложения:

Идём дальше. Чтобы добавить разные классы для разных версий, нужно сначала создать соответствующую файловую структуру, например, src/free/java и src/pro/java .

Обратите внимание, что в отличие от ресурсов, нельзя создать один и тот же класс в папке main и, например, в папке pro . Возникнет ошибка дублирования. Если вам нужно иметь модификацию одного класса для разных версий, то создавайте в каждой из веток свою версию этого класса, а из папки main его убирайте. После выбора нужного Build Variant соответствующая ветка станет активной:

Источник

Android: создание динамических Product Flavors и Signing Configs

При работе над Android-проектом, представляющий собой платформу для создания приложений для просмотра видео-контента, возникла необходимость динамического конфигурирования product flavors с выносом информации о signing configs во внешний файл. Подробности под катом.

Исходные данные

Имеется Android-проект, представляющий собой платформу для создания приложений для просмотра видео-контента. Кодовая база общая для всех приложений, различия заключаются в настройках параметров REST API и настройках внешнего вида приложения (баннеры, цвета, шрифты и т.д.). В проекте использованы три flavor dimension:

  1. market: «google» или «amazon». Т.к. приложения распространяются как в Google Play, так и в Amazon Marketplace, имеется необходимость разделять некоторый функционал в зависимости от места распространения. Например: Amazon запрещает использование In-App Purchases механизма от Google и требует реализацию своего механизма.
  2. endpoint: «pro» или «staging». Специфические конфигурации для production и staging версий.
  3. site: собственно dimension для конкретного приложения. Задается applicationId и signingConfig.

Проблемы с которыми мы столкнулись

При создании нового приложения необходимо было добавить Product Flavor:

Также, необходимо было добавить соответствующий Signing Config:

Проблемы:

Вынос информации о сертификатах

Первым шагом был вынос информации о сертификатах в отдельный json-файл. Для примера информация так-же хранится в plain-text, но ничего не мешает хранить файл в зашифрованном виде (мы используем GPG) и расшифровывать непосредственно во время сборки приложения. JSON-файл имеет следующую структуру:

Секцию signingConfigs в build.gradle файле удаляем.

Упрощение Product Flavors секции

Для сокращения количества строк, необходимых для описания Product Flavor с dimension = «site», был создан массив с необходимой информацией для описания конкретного приложения, а все Product Flavors с dimension=»site» были удалены.
Было:

Динамическое создание Product Flavors

Последним шагом оставалось динамически создавать product flavors и signing configs используя внешний JSON-файл с информацией о сертификатах из массива applicationDefinitions.

Читайте также:  Байки мэтра для андроид

Для добавления чтения из зашифрованного хранилища необходимо заменить секцию

Источник

Creating Different Build Variants in Android

While developing an Android application, we generally need various types of APKs or you can say different versions of APK during the development and release phase. For example, you may need one debug APK without having proguard or one debug APK with proguard or you may need one APK for your free users and one APK for your paid users or you may need one APK for Android version 6 and above and one APK for Android version below 6 and there are many other possibilities. But the question is, how you are going to create these many versions of your App. Are you going to have different projects for these versions or just one project is enough? Because the code is going to remain almost the same and just some APIs or some build configurations are going to change? So, how to achieve this? This can be achieved by using Build Variants i.e. the topic of this blog.

In this blog, we are going to learn what Build Variants are and how to create different build variants in Android. So, let’s get started.

Build Types and Build Variants

While building any Android application, we create various build types such as «debug» and «release». At the same time, we can create various product flavors for the same app, for example, the free product flavor for free users and the paid product flavor for the paid users. So, Android Studio provides a feature of Build Variants which can be thought of as a cartesian product of all your build types and all your product flavors.

All you need to do is add various build types in your module-level build.gradle file and during development or production, you can simply choose the Build Variant you want to test or release.

NOTE: By default, the Android Studio will generate » debug» and » release» Build Types for your project.

The Build Variant option can be found at the left part of the screen(mostly below Resource Manager)in Android Studio or go to Build > Select Build Variant or you can simply press cmd + shift + A and search for «Build Variant»:

So, to change a Build Type, all you need to do is just select your Build Type from the Build Variant and after the project sync, you are good to go. But how to create a Build Type? Let’s see.

Add Build Types

In this section, we are going to learn how to add various build types in Android.

By default, whenever you create any project, then Android Studio will create two build types for the project i.e. » debug» and » release«. But in order to add more build types, you need to add them to your module-level build.gradle file and under the buildTypes block. The following is an example of the same:

In the above code, there are three build types i.e. debug, release, and minifiedDebug. The debug and release are the same generated by Android Studio with some additional properties and minifiedDebug is the new build type that is a combination of debug + proguard.

If you closely look at the code, then you will find that in the defaultConfig block, the version name is «0.0.3» and in the debug and minifedDebug build type, we are adding a «.dev» suffix to the version name. This will differentiate the dev APK from the prod APK.

Similarly, you can create the build type named noMinifedRelease that will be a combination of release + without proguard.

Читайте также:  Doogee bl7000 обновление андроид

There are certain cases where you want to use the same properties of some of your previous build types and add or modify some properties to create a new build type. So, to do so you can use initWith :

The above is the code of a new build type name newBuildType. Since we are using initWith debug , so it will contain all the properties of debug and you can add more properties to it or you can also edit some of the properties of debug and keep other things as it is. In our case, we are editing the versionNameSuffix and setting it with » .newbuild» instead of » .dev» that is there in the debug.

Now, if you open the Build Variants option in the Android Studio, then you will find 4 build variants i.e. debug, release, minifiedDebug, and newBuildType. You can choose any of these for your build.

NOTE: If you are using Kotlin DSL in your build.gradle file, then to add a build type, you need to use create(«yourBuildTypeName») method in buildTypes block.

Adding Product Flavors

You can think of Product Flavors as different variants of your app. i.e. if you are providing different content to different users but using the same code base, then you can add product flavors to your app.

For example, you can add product flavors such as » development» and » production«, Inside these flavors you can add different API keys for the same working flow. For example, you can add the development API in the development flavor and production API in the production flavor.

To add a product flavor you need to add the productFlavors block inside the android block and each product flavor must have some flavor dimension:

The best part of product flavors is that they are associated with build types. For example, if you have two build types named «debug» and «release» and two product flavors named «development» and «production», then your build variants will be:

  • developmentDebug
  • developmentRelease
  • productionDebug
  • productionRelease

Now, you can select any of the build variants you want for your build.

You can create as many product flavor dimensions as you want by separating each dimension from others by using a comma( , ) and use it by using dimension «dimensionName» . For example:

So, this is how you can create a product flavor and use it in your app for making various versions.

That’s it for this blog.

If you want to learn about build variants by watching from video, you can watch our video from MindOrks YouTube channel .

Источник

Android Flavors

Motivation

Sometimes you have to deliver application for multiple environments, demo/full features and other configurations. Configuring this manually before build is not a good idea and here appears problem with Continuous Delivery and Continuous Deployment.

Let’s imagine that we have an application which works with some API endpoint and we should also delivered in Demo/Full mode.

Intro

The Android build system compiles app resources and source code and packages them into APKs that you can test, deploy, sign, and distribute. Android Studio uses Gradle as a build system.

Gradle is an open source build automation system that builds upon the concepts of Apache Ant and Apache Maven and introduces a Groovy-based domain-specific language ( DSL) instead of the XML form used by Apache Maven of declaring the project configuration. Gradle uses a directed acyclic graph (“DAG”) to determine the order in which tasks can be run.

Gradle Project Structure

Although we won’t go deep into this topic, we will need some basic knowledge about project structure.

Flavor

Build variants are the result of Gradle using a specific set of rules to combine settings, code, and resources configured in your build types and product flavors. Although you do not configure build variants directly, you do configure the build types and product flavors that form them.

Читайте также:  Звуки для андроид разблокировки экрана

Although you can find some documentation of this in references, I will make a brief information of flavors definition and configuration.

build.gradle

Gradle build configuration file. You can see such one in project and inside modules. Also, here you can also find settings.gradle which defines what modules to include. In my case, MyProject has content :

This means that our project includes app module.

Defining flavors

Let’s create a sample application which will be compound of 2 versions, Full and Demo.

Add following lines of code in builld.gradle of App Module. These Flavors are added in default dimension(will cover this topic later).

After adding this, in Android Studio Gradle Tasks you can find under :app section following tasks.

You can use terminal to check build tasks, to run

and get following output under Build Tasks

Configuration is done. What’s next ?

One we had made have configured successfully, it’s time to define something specifics for this flavors. Into Android Studio project explorer, switch to “Project” mode and create following hierarchy

This means we had defined some specific strings for Demo mode and some for Full Mode.

Content of strings.xml in demo

Content of strings.xml in full

Great, now you can switch to “Android” mode in Project Explorer. And now open “Build variants” panel in AS and you should have following variants:

You see here combination of flavors with build types, that’s OK. Select one of them and try to run application in your device. For Demo variant you’ll have application with name Demo App and for Full you’ll have Full App.

Try to install both flavors in your phone, you’ll see that it’s not overriden, but we have 2 different apps called “Demo App” and “Full App”. That’s because we had specified applicationId property for both variants and they had different ID-s.

In same way you can define flavor specific resources,activities, manifest and … everything you want. Note that you Gradle will Flavor Specifics with defaults. For checking this, try to build an apk and analyze it with Android Studio.

Furthermore, you can specify resources for Demo variant and Debug Build Type. For this, you should create directory in

Flavor dimensions

In previous step we had defined 2 flavors “demo”, “full” but sometimes you need more flexibility. What if we will need more flexibility and to deliver following applications :

  • Demo App pointing to Live Environment
  • Full App pointing to Test Environment
  • or other configuration.

Here we can observe that we need another layer of flavors. Here comes in help flavor dimensions. You can think this in terms of “category”. Let’s update our app/gradle.config to be

We defined added 2 dimensions “type” and “environment”.

Now, you’ll have following variants(also you can check gradle tasks, you’ll see same result). You can find here that Gradle mixed our dimensions with build types and we obtained following combinations

If this still doesn’t tell you nothing, then you can think that Gradle gives you following combinations

Specifying resources

Android plugin allows you to combine different flavors, but you still need to take care of naming conventions, here I denoted some of them. You can have more than 2 flavors, you can use in your own purpose.

Final word

We all know how great is Gradle and how much flexibility it gives to us. Additionally Android Plugin offers us Flavors for creating combinations of configurations. This can be useful when you have to deliver multiple types of application like in our example. This also gives you possibility automate everything for Continuous Delivery and Continuous Deployment.

Источник

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