Let's say say we want to change
a compile flag in our Java project.
We can just add some configuration
to the compile Java task.
However, unlike simple Java projects,
which have a finite set of tasks such
as, compile Java, jar, test, etc.
Android projects can have
an indeterminate number of tasks,
depending on the build types and
product flavors we have declared.
Additionally, the names of
these tasks are generated, and
they're based on the name of
the particular variant the task is for.
Not only that, but these tasks
are created at a very late stage of
the project configuration life cycle.
Which means, in most cases,
we can't directly reference
them in our build script.
Essentially, we need
to solve two problems.
First, we need a way to reference each
task used to build a particular variant
without having to know
the task's actual name.
Quite simply, we want to configure all
the tasks of a particular type for
every variant.
Second, we need a way to defer
the configuration of that task
until after all of our build
variants have been created.
Which really just means that we can't
configure the task until a task exists.
The first problem is solved by
the Android Gradle Plugin itself,
which groups all the information
to include the tasks
associated with any given
variant into a single object.
There are three main types of these
objects, the Application Variant,
the Library Variant or the Test Variant.
The type of variant we need depends on
the type of project we're building.
Application Variants and
Library Variants are created for Android
Applications or libraries respectively.
And Test Variants are created for
the on device test APK.
Each one has its own specific
properties, but they all have common
tasks, like compiling Java,
merging resources, and so on.
So the Android Griddle plugin is
nice enough to neatly package all
the information about a variant for
us, but the problem remains, how do
we reference these variant objects?
This problem is solved by what
Gradle calls live collections.
Essentially, as the Android
plugin creates variants,
they are added to a fancy
type of collection.
These collections allow us
to define configurations for
objects that don't yet exist.
Instead, Gradle will remember
our configuration and
execute it when a new object is added.
We specify this configuration
by calling the all method
on our variant collection.
For example, if we wanted to configure
all the Java compile tasks for
our application variants
to add a compiler argument,
we could do something like this.
This will now configure each Java
compile task for each of our debug build
types, regardless of how many
product flavors we have configured.
Also, you don't have to try and
guess what the final names of
each of those tasks might be.
لنقل أننا نريد أن نغير
.تجميع العلامات في مشروع Java لدينا
يمكننا إضافة تكوين
.إلى تجميع مهمة Java
لكن على عكس بعض مشروعات Java البسيطة
التي تضم مجموعة من المهام مثل
.تجميع Java وjar واختبار...إلخ
يمكن لمشروعات Android
أن يكون لديها عدد غير محدود من المهام
تعتمد على أنواع البنية
.وصفات المنتج التي بيناها
بالإضافة إلى ذلك، يتم إنشاء أسماء
هذه المهام
وهي تعتمد على اسم
.المتغير الخاص الذي تتعلق به المهمة
وليس هذا فحسب، ولكن يتم إنشاء هذه المهام
في مرحلة متأخرة جدًا من
.دورة حياة تكوين المشروع
وهذا يعني في معظم الحالات
أننا لا نستطيع إحالتها مباشرةً
.في البرنامج النصي للبنية
كما أننا نحتاج بالضرورة
.إلى حل مشكلتين
أولاً، نحتاج إلى طريقة لإحالة كل
مهمة مستخدمة لبناء متغير خاص
دون الحاجة إلى معرفة
.اسم المهمة الفعلي
ونريد ببساطة أن نضبط جميع
مهام نوع معين
.لكل متغير
ثانيًا، نحتاج إلى طريقة لتأخير
ضبط هذه المهمة
حتى يتم إنشاء جميع
.متغيرات البنية
الأمر الذي يعني أننا لا نستطيع
.ضبط المهمة حتى يتم إنشاؤها
يتم حل المشكلة الأولى
،بواسطة المكون الإضافي لـ Android Gradle
الذي يجمع كل المعلومات
لتضمين المهام
المصاحبة لأي متغير
.معطى إلى كائن فردي
هناك ثلاثة أنواع رئيسية من هذه
الكائنات أو متغير التطبيق
.أو متغير المكتبة أو متغير الاختبار
يعتمد نوع المتغير الذي نحتاجه على
.نوع المشروع الذي نبنيه
يتم إنشاء متغيرات التطبيق
ومتغيرات المكتبة لتطبيقات Android
.أو مكتباته على التوالي
كما يتم إنشاء متغيرات الاختبار
.لـ APK الاختبار الذي يتم في الجهاز
ولكل منها خصائصها
المحددة، لكنها جميعًا لديها مهام
مشتركة مثل تجميع Java
.ودمج المصادر وغير ذلك
إن المكون الإضافي الخاص بـ Android Griddle
رائع بما يكفي لتجميع كل
،المعلومات عن المتغير
ولكن مازال هناك مشكلة وهي كيفية
.إحالة كائنات المتغيرات إلى مصدرها
يتم حل هذه المشكلة بما يستدعيه
.Gradleمن المجموعات المباشرة
وبالضرورة بينما يُنشئ المكون الإضافي لـ Android
متغيرات
يتم إضافتها إلى نوع رائع
.من المجموعات
تتيح لنا هذه المجموعات
تحديد التكوينات
.للكائنات التي لم تُنشأ بعد
وبدلاً من ذلك، سيتذكر Gradle
التكوين
.وينفذه عند إضافة كائن جديد
ونحدد هذا التكوين
باستدعاء جميع الطرق
.إلى مجموعة المتغيرات
على سبيل المثال، إذا أردنا ضبط
جميع مهام Java المجمعة
لمتغيرات التطبيق
لإضافة وسيطة محول برمجي
.يمكننا فعل شيء كهذا ،
وسيقوم ذلك بضبط
كل مهمة تجميع Java لكل أنواع بنية تصويب الأخطاء
بغض النظر عن عدد صفات المنتج
.التي قمنا بضبطها
كما أنكم غير ملزمين بمحاولة
وتخمين الأسماء النهائية
.لكل من تلك المهام
Digamos que queiramos mudar
um sinalizador de compilação no projeto Java.
Podemos apenas adicionar configuração
à tarefa compile Java.
No entanto, diferente de projetos Java simples
que têm um conjunto finito de tarefas
como, compile Java, jar, test etc.
Projetos Android podem ter
um número indeterminado de tarefas,
dependendo dos tipos de compilação
e sabores do produto que declaramos.
Além disso, os nomes dessas
tarefas são gerados e são baseados
no nome da variante específica
para qual é a tarefa.
Além disso, essas tarefas são
criadas muito mais tarde no ciclo de vida
da configuração do projeto.
O que significa, na maioria dos casos,
que não podemos fazer
referência direta a elas em nosso script de compilação.
Basicamente, precisamos
resolver dois problemas.
Primeiro, precisamos de um modo de fazer
referência a cada tarefa usada na compilação
de determinada variante sem ter
de saber o nome real da tarefa.
Simplesmente queremos configurar
todas as tarefas de determinado tipo
para todas as variantes.
Depois, precisamos de um modo
de adiar a configuração da tarefa
até depois da criação de todas
as variantes da compilação.
O que significa que não podemos
configurar a tarefa até que ela exista.
O primeiro problema é resolvido
pelo próprio plugin Gradle do Android,
que agrupa todas as informações
para incluir as tarefas
associadas a qualquer variante
em um objeto único.
Há 3 tipos principais desses objetos,
Variante de aplicativo,
Variante de biblioteca e o Variante de teste.
O tipo de variante que precisamos depende
do tipo de projeto que estamos compilando.
Variantes de aplicativo e
Variantes de biblioteca são criadas para
Aplicativos ou bibliotecas do Android respectivamente.
E as Variantes de teste são criadas
para APK de teste de dispositivo.
Cada uma tem suas propriedades
específicas mas todas tem tarefas
comuns, como compilação de Java,
mescla de recursos etc.
O plugin do Android Griddle é
muito legal e agrupa de modo ordenado todas
as informações sobre uma variante para nós,
mas o problema continua, como
fazemos referência a esses objetos de variante?
O problema é resolvido por aquilo
que o Gradle chama de coleções ativas.
Basicamente, como o plugin do
Android cria variantes,
elas são adicionadas a
um tipo especial de coleção.
Essas coleções nos permitem
definir configurações para
objetos que ainda não existem.
Em vez disso, Gradle lembra
da configuração e a executa
quando um novo objeto é adicionado.
Especificamos essa configuração
chamando o método all
em nossa coleção de variantes.
Por exemplo, se quisermos configurar
todas as tarefas de compilação Java para
nossas variantes de aplicação
adicionarem um argumento de compilador,
fazemos algo deste tipo.
Isso vai configurar cada tarefa Java.compile
para cada tipo de compilação debug,
independente de quantos
sabores de produto tivemos configurado.
Além disso, você não precisa
tentar adivinhar qual deve ser
os nomes finais de cada uma das tarefas.
假设我们想更改
Java 项目中的编译标记。
我们只需向 Java
编译任务中添加一些配置即可。
Java 项目的任务数量是确定的,
例如编译 Java、jar、test 等。
但 Android 项目不同于一般的 Java 项目,
Android 项目的
任务数量是不确定的,
取决于我们声明的
构建类型和产品风格。
此外,这些任务
的名称已生成,而
这些名称则是基于任务
所代表的特定变量生成的。
不仅是名称,这些任务
也是在项目配置生命周期的
末期创建的。
这意味着,在大多数情况中,
我们无法直接在
构建脚本时引用这些任务。
从根本上来说,
我们需要解决两个问题。
首先,我们需要可以
引用不需要知道任务的
实际名称就能用于构建
特定变量的每个任务的方式。
这个非常简单,我们
只需为每个变量配置
特定类型的所有任务。
其次,我们需要能
在所有构建变量都建立后,
再对相应任务
进行配置的方式。
这种方式意味着,在某个任务
存在前,我们无法对其进行配置。
对于第一个问题,
通过将所有
要包括到与所给任意
变量相关的任务中的信息
组合至单个对象中的方式,
Android Gradle 插件可自行解决。
这些对象的类型
主要有三种,即 Application Variant、
Library Variant 或 Test Variant。
我们需要哪种类型的变量
取决于我们构建的项目类型。
Application Variant 和
Library Variant 分别是为
Android 应用程序和库创建的。
而 Test Variant 则是为
设备上的 APK 测试创建的。
每个变量都有其
特定的属性,但它们也可以
执行常见的任务,
例如编译 Java、合并资源等。
因此,Android Griddle 插件
已非常完美,足以稳妥得为我们
打包某个变量的所有信息,
但仍然存在的问题是,
我们如何引用这些变量对象呢?
被 Gradle 称之为
“实时集合”的程序可解决这个问题。
实际上,随着
Android 插件创建变量,
这些变量将被
添加到一个奇特的集合中。
这些集合允许我们
为不存在的对象
定义配置。
Gradle 将记住
这些配置,并在添加了
新对象时执行这些配置。
通过呼叫
变量集合中的 all 方法,
我们可以指定此配置。
例如,如果我们
想为应用程序变量配置
所有 Java 编译任务,
以添加编译器参数时,
我们就可以执行类似操作。
不管我们配置了
多少种产品风格,这种方法
现在都可以为每个调试版本
类型配置每个 Java 编译任务。
您也就没有必要
猜测每个任务
的最终名称是什么了。