Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Confira abaixo alguns recursos que estão disponíveis na maioria dos sistemas de CI.
Ambiente
É importante escolher e entender o ambiente de hardware e software em
que o sistema executa o fluxo de trabalho. Considerações importantes para aplicativos
Android são:
Plataforma: Linux, Mac, Windows e as versões deles.
Memória disponível: a criação de apps e a execução de emuladores pode usar muita memória RAM,
e geralmente é necessário ajustar parâmetros, como o tamanho de heap da JVM, para
evitar erros de falta de memória.
Software pré-instalado: os sistemas de CI geralmente fornecem imagens com um grande
conjunto de ferramentas já disponíveis, como o Java Development Kit (JDK),
o Android Software Development Kit (SDK), ferramentas de build, plataformas e
emuladores.
Arquitetura do executor e conjunto de instruções: ARM, x86. Isso é importante ao
usar emuladores.
Variáveis de ambiente: algumas são definidas pelo sistema de CI (por exemplo:
ANDROID_HOME) e podem ser definidas por conta própria para, por exemplo, evitar a fixação de credenciais
no código do fluxo de trabalho.
Há muitos outros aspectos que precisam ser considerados, como o número de núcleos
disponíveis e se a virtualização está ativada para executar emuladores.
Registros e relatórios
Quando uma etapa falha, o sistema de CI notifica você e, geralmente, não permite que você mescle
a alteração. Para descobrir o que deu errado, procure erros nos registros.
Além disso, a criação e o teste geram relatórios que geralmente são armazenados como
artefatos desse build específico. Dependendo do sistema de CI, você pode usar plug-ins para visualizar os resultados desses relatórios.
Tempos de execução de cache e CI
Os sistemas de CI usam um cache de build para acelerar o processo. Na forma mais simples, eles
salvam todos os arquivos de cache do Gradle após um build bem-sucedido e os restauram antes
de um novo. Isso depende do recurso de cache de build do Gradle (link em inglês) e precisa ser
ativado no seu projeto.
Confira algumas maneiras de melhorar os tempos de execução e a confiabilidade:
Módulos: detectar quais módulos são afetados por uma mudança e
apenas criar e testar.
Pular caches: se o build incluir scripts que um desenvolvedor modificou,
ignore os caches de build. É mais seguro criar do zero.
Testes de fragmento: especialmente testes instrumentados, pode ser útil fragmentar
testes em vários dispositivos. Isso é compatível com o executor do Android, dispositivos
gerenciados pelo Gradle e o Firebase Test Lab.
Builds de fragmento: é possível fragmentar o build em várias instâncias de servidor.
Instabilidade refere-se a testes ou ferramentas que falham intermitentemente. Sempre
tente encontrar e corrigir os problemas que geram builds e testes instáveis, mas alguns
deles são difíceis de reproduzir, especialmente ao executar testes instrumentados.
Uma estratégia comum é repetir as execuções de teste sempre que elas falharem, até um número
máximo de tentativas.
Não há uma maneira única de configurar novas tentativas, porque elas podem ocorrer em vários
níveis. A tabela a seguir descreve a ação que você pode realizar em resposta a uma
falha no teste instável:
Falha
Ação
O emulador não respondeu por um segundo, acionando um tempo limite
Executar novamente o teste com falha
Falha ao inicializar o emulador
Executar toda a tarefa novamente
Ocorreu um erro de conexão durante a fase de finalização da compra do código
Reiniciar o fluxo de trabalho
É importante registrar e monitorar quais partes do sistema estão instáveis e
investir para manter a CI confiável e rápida, contando apenas com novas tentativas
O conteúdo e os exemplos de código nesta página estão sujeitos às licenças descritas na Licença de conteúdo. Java e OpenJDK são marcas registradas da Oracle e/ou suas afiliadas.
Última atualização 2025-07-27 UTC.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-07-27 UTC."],[],[],null,["# CI features\n\nThe following are some features that you can find in most CI systems.\n\nEnvironment\n-----------\n\nIt's important to choose and understand the hardware and software environment in\nwhich the system executes the workflow. Important considerations for Android\napplications are:\n\n- **Platform**: Linux, Mac, Windows, and their versions.\n- **Available memory**: Building apps and running emulators can use a lot of RAM and it's often necessary to tweak parameters such as the JVM's heap size to avoid out-of-memory errors.\n- **Preinstalled software**: CI systems usually provide images with a large collection of tools already available, such as the Java Development Kit (JDK), the Android Software Development Kit (SDK), build tools, platforms and emulators.\n- **Runner architecture and instruction set**: ARM, x86. This is important when using emulators.\n- **Environment variables** : Some are set by the CI system (for example: `ANDROID_HOME`) and you can set your own to, for example, avoid hardcoding credentials in your workflow.\n\nThere are many other aspects you should consider, such as the number of cores\navailable, and whether virtualization is enabled to run emulators.\n\nLogs and reports\n----------------\n\nWhen a step fails, the CI system notifies you and usually doesn't let you merge\nthe change. To find out what has gone wrong, look for errors in the logs.\n\nAdditionally, building and testing generates reports that are usually stored as\nartifacts of that particular build. Depending on the CI system, you can use\nplugins to visualize the results of those reports.\n\nCache and CI run times\n----------------------\n\nCI systems use a build cache to speed up the process. In its simplest form, they\nsave all the Gradle cache files after a successful build and restore them before\na new one. This relies on [Gradle's build cache](https://docs.gradle.org/current/userguide/build_cache.html) feature and should be\nenabled in your project.\n| **Note:** take into account the time that it takes for the cache to download as, if the cache becomes too big and it contains more than is necessary, it could be detrimental to the overall build time.\n\nSome ways to improve run times and reliability include:\n\n- **Modules**: Detecting which modules are affected by a change and only building and testing those.\n- **Skip caches**: If the build includes scripts that a developer has modified, ignore the build caches. It's safer to build from scratch.\n- **Shard tests**: Especially instrumented tests, it can be helpful to shard tests across multiple devices. This is supported by the Android runner, Gradle Managed Devices and Firebase Test Lab.\n- **Shard builds**: You can shard the build across multiple server instances.\n- **Remote cache** : You can also use [Gradle's remote cache](https://docs.gradle.org/current/userguide/build_cache.html).\n\nRetry failed tests\n------------------\n\nFlakiness refers to tests or tools that fail intermittently. You should always\ntry to find and fix the problems that generate flaky builds and tests, but some\nof them are difficult to reproduce, especially when running instrumented tests.\nA common strategy is to retry test runs whenever they fail, up to a maximum\nnumber of retries.\n\nThere is no single way to configure retries, as they can occur at multiple\nlevels. The following table outlines the action you might take in response to a\nflaky test failure:\n\n| Failure | Action |\n|--------------------------------------------------------------|-----------------------|\n| Emulator was unresponsive for a second, triggering a timeout | Rerun the failed test |\n| Emulator failed to boot | Rerun the whole task |\n| There was a connection error during the code checkout phase | Restart the workflow |\n\nIt's important to log and keep track of which parts of the system are flaky and\ninvest in keeping CI reliable and fast, only relying on retries"]]