- Installing Gradle
- Prerequisites
- Installing with a package manager
- Installing manually
- Step 1. Download the latest Gradle distribution
- Step 2. Unpack the distribution
- Linux & MacOS users
- Microsoft Windows users
- Step 3. Configure your system environment
- Linux & MacOS users
- Microsoft Windows users
- Verifying installation
- Next steps
- Установите Gradle вручную и используйте его в Android Studio
- Getting Started with Gradle
Installing Gradle
You can install the Gradle build tool on Linux, macOS, or Windows. This document covers installing using a package manager like SDKMAN! or Homebrew, as well as manual installation.
Use of the Gradle Wrapper is the recommended way to upgrade Gradle.
You can find all releases and their checksums on the releases page.
Prerequisites
Gradle runs on all major operating systems and requires only a Java Development Kit version 8 or higher to run. To check, run java -version . You should see something like this:
Gradle ships with its own Groovy library, therefore Groovy does not need to be installed. Any existing Groovy installation is ignored by Gradle.
Gradle uses whatever JDK it finds in your path. Alternatively, you can set the JAVA_HOME environment variable to point to the installation directory of the desired JDK.
Installing with a package manager
SDKMAN! is a tool for managing parallel versions of multiple Software Development Kits on most Unix-like systems (macOS, Linux, Cygwin, Solaris and FreeBSD). We deploy and maintain the versions available from SDKMAN!.
Homebrew is «the missing package manager for macOS».
Other package managers are available, but the version of Gradle distributed by them is not controlled by Gradle, Inc. Linux package managers may distribute a modified version of Gradle that is incompatible or incomplete when compared to the official version (available from SDKMAN! or below).
Installing manually
Step 1. Download the latest Gradle distribution
The distribution ZIP file comes in two flavors:
Complete (all) with docs and sources
Need to work with an older version? See the releases page.
Step 2. Unpack the distribution
Linux & MacOS users
Unzip the distribution zip file in the directory of your choosing, e.g.:
Microsoft Windows users
Create a new directory C:\Gradle with File Explorer.
Open a second File Explorer window and go to the directory where the Gradle distribution was downloaded. Double-click the ZIP archive to expose the content. Drag the content folder gradle-7.3.1 to your newly created C:\Gradle folder.
Alternatively, you can unpack the Gradle distribution ZIP into C:\Gradle using an archiver tool of your choice.
Step 3. Configure your system environment
To run Gradle, the path to the unpacked files from the Gradle website need to be on your terminal’s path. The steps to do this are different for each operating system.
Linux & MacOS users
Configure your PATH environment variable to include the bin directory of the unzipped distribution, e.g.:
Alternatively, you could also add the environment variable GRADLE_HOME and point this to the unzipped distribution. Instead of adding a specific version of Gradle to your PATH , you can add $GRADLE_HOME/bin to your PATH . When upgrading to a different version of Gradle, just change the GRADLE_HOME environment variable.
Microsoft Windows users
In File Explorer right-click on the This PC (or Computer ) icon, then click Properties → Advanced System Settings → Environmental Variables .
Under System Variables select Path , then click Edit . Add an entry for C:\Gradle\gradle-7.3.1\bin . Click OK to save.
Alternatively, you could also add the environment variable GRADLE_HOME and point this to the unzipped distribution. Instead of adding a specific version of Gradle to your Path , you can add %GRADLE_HOME%/bin to your Path . When upgrading to a different version of Gradle, just change the GRADLE_HOME environment variable.
Verifying installation
Open a console (or a Windows command prompt) and run gradle -v to run gradle and display the version, e.g.:
You can verify the integrity of the Gradle distribution by downloading the SHA-256 file (available from the releases page) and following these verification instructions.
Next steps
Now that you have Gradle installed, use these resources for getting started:
Create your first Gradle project by following one of our step-by-step samples.
Sign up for a live introductory Gradle training with a core engineer.
Learn how to achieve common tasks through the command-line interface.
Configure Gradle execution, such as use of an HTTP proxy for downloading dependencies.
Subscribe to the Gradle Newsletter for monthly release and community updates.
Источник
Установите Gradle вручную и используйте его в Android Studio
Я использую Android Studio. Как я могу вручную установить и использовать Gradle внутри Android Studio .
Я скачал Gradle с http://www.gradle.org/downloads версию gradle-2.1-all.zip.
Когда я открываю заархивированный файл, я вижу корзину, документы и т. Д., Но не знаю, куда их скопировать. И даже после копирования, как его использовать в Android ..
Android Studio будет автоматически использовать оболочку Gradle и извлекать правильную версию Gradle, а не использовать локально установленную версию. Если вы хотите использовать новую версию Gradle, вы можете изменить версию, используемую студией. Под деревом проекта Android Studio откройте файл gradle/wrapper/gradle-wrapper.properties . Измените эту запись:
Загрузите последний файл распространения Gradle и извлеките его, затем скопируйте все файлы и вставьте его в:
Шаг 1. Перейдите на сайт загрузки из Gradle: https://gradle.org/releases/
Шаг 2: Извлеките загруженный zip-файл в каталог.
Шаг 2: нажмите Ctrl + Alt + S (mac: ⌘ +,) в Android Studio / Intellij IDEA
Шаг 3: Goto: Build, Execution, Deployment >> Build Tools >> Gradle (или просто введите Gradle в строке поиска)
Шаг 4: Выберите: (X) Использовать локальное распространение Gradle и установите Gradle домой в извлеченный каталог Gradle. Нажмите «Применить».
Шаг 5: Избавьтесь от ненужных файлов gradle, удалите:
— MyApp / gradle /
— gradlew
— gradlew.bat
Предполагая, что это система Windows, и мы используем gradle-2.1-all [Применимо к любой версии Gradle, просто измените версию по мере необходимости]
Установите \gradle\wrapper\gradle-wrapper.properties флажок Убедитесь, что значение distributionUrl равно
Этого достаточно, поскольку он автоматически загрузит градиент.
После выполнения вышеуказанных действий, если вы скачали zip- архив , вставьте gradle-2.1-all.zip в
Это сэкономит дополнительное время на загрузку.
1.Скачайте Gradle- распределение формы Gradle
2. извлеките файл в какое-то место
3. Откройте Android Studio : Файл> Настройки> Gradle> Использовать локальное распределение Gradle перейдите по пути, по которому вы извлекли Gradle.
4. нажмите Применить и ОК
Я использовал вот так,
И это сработало для меня.
Распакуйте его где угодно. В Android Studio в разделе «Настройки» есть категория Gradle, где вы можете указать внешнее расположение Gradle, если хотите. Вероятно, имеет смысл поместить папку Gradle bin на свой путь.
Шаг 1. Загрузите последнюю версию Gradle.
Шаг 2. Распаковать дистрибутив
Пользователи Microsoft Windows
Создайте новый каталог C: \ Gradle с помощью проводника.
Откройте второе окно проводника и перейдите в каталог, в который был загружен дистрибутив Gradle. Дважды щелкните ZIP-архив, чтобы открыть содержимое. Перетащите папку содержимого gradle-4.1 во вновь созданную папку C: \ Gradle.
В качестве альтернативы вы можете распаковать ZIP-архив с дистрибутивом Gradle в C: \ Gradle, используя любой архиватор по вашему выбору.
Шаг 3. Настройте системную среду
Пользователи Microsoft Windows
В проводнике щелкните правой кнопкой мыши значок «Этот компьютер (или компьютер)», затем выберите «Свойства» -> «Дополнительные параметры системы» -> «Переменные среды».
В разделе «Системные переменные» выберите «Путь» и нажмите «Изменить». Добавьте запись для C: \ Gradle \ gradle-4.1 \ bin. Нажмите ОК, чтобы сохранить.
Шаг 4. Проверьте установку.
(В существующих ответах упоминаются 2 решения, которые могут работать, но предпочтительное из них — вручную загрузить gradle для gradlew , отсутствие важных деталей и вызвать сбой. Итак, я бы добавил сводку с недостающими деталями, чтобы сэкономить ненужное потраченное время , на случай, если другие столкнутся с той же проблемой.)
Есть 2 возможных решения:
Решение A. Используйте местоположение gradle и удалите gradlew связанные файлы. (не рекомендую)
Обратитесь к этому ответу из этого сообщения: https://stackoverflow.com/a/29198101/
Подсказки:
- Я пробовал, это работает, хотя в целом это не рекомендуется для использования Gradle.
- И с этим решением каждый раз при открытии проекта android-studio будет запрашивать подтверждение, использовать ли вместо этого gradlew, это немного раздражает.
Решение Б. Загрузите gradle дистрибутив вручную для gradlew . (рекомендуемые)
Android Studio загрузит gradle в подкаталог, названный хешем.
Чтобы загрузить вручную, необходимо выполнить загрузку в точную подкаталог, названный хешем.
Шаги:
- Получите хеш.
- Запускаем android-studio.
- Создайте базовый проект.
- Затем он создаст хеш и начнет загрузку gradle.
например .gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/ - Закройте android-studio.
- Найдите процесс загрузки от android-studio.
например ps -aux grep | android - Убейте все связанные процессы Android.
- Удалите пустой проект.
- Скачайте gradle вручную.
- Зайдите в хеш-папку.
например .gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/ - Есть частично загруженный файл.
например gradle-4.10.1-all.zip.part - Скачайте точную версию вручную.
с веб-сайта: https://services.gradle.org/distributions/
например https://services.gradle.org/distributions/gradle-4.10.1-all.zip - Удалите *.part файл.
- И скопируйте туда файл загрузки.
например .gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/gradle-4.10.1-all.zip
- Зайдите в хеш-папку.
- Начни Android Studio и попробуй еще раз.
- Снова создайте новый пустой проект.
- Тогда больше не нужно загружать gradle.
- Он будет распаковывать gradle в том же каталоге.
например .gradle/wrapper/dists/gradle-4.10.1-all/455itskqi2qtf0v2sja68alqd/gradle-4.10.1/ - И начинает синхронизировать зависимости, индексацию и сборку.
Подсказки:
- После перезапуска Android Studio и повторного создания пустого проекта, если вы видите, отображается сообщение «Ожидание загрузки дистрибутива другим процессом».
Это означает, что вы не прервали предыдущий процесс загрузки, сначала завершили его, затем удалили пустой проект, а затем создали новый проект для повторного подтверждения. - Каждая версия Android Studio может использовать разные gradle версии, поэтому может потребоваться повторить этот процесс один раз при Android Studio обновлении.
Кстати :
Вот макет каталога на моем Linux
(для Android Studio 3.3.1 , использующем gradle 4.10.1)
/.gradle/wrapper $ tree -L 4
Предложения Android-Studio
- Поскольку при загрузке Gradle дистрибутив внутри Android Studio .
Лучше предоставить возможность выбрать локальный gradle установочный каталог или файл .zip для использования gradlew .
Источник
Getting Started with Gradle
Gradle is a powerful new dependency management system for Java. It provides the ability to provide more custom build logic than predecessors such as Maven or Ant.
Android Studio uses an Android Gradle plugin that handles most of the integration with Gradle. This plugin allows you to build different versions of your app (i.e. paid and unpaid, custom builds for different Android devices) while still leveraging the same code base. It also enables signing your APK and code obfuscation support too, as well as many other features.
When importing existing Android Studio projects, you should make sure to select the build.gradle in the top-level directory. If you choose this option, you should see the Use default gradle wrapper option exposed and will be able to import the project properly. If you select on a folder or even the app/build.gradle file, you are likely to import a blank project and will need to redo the import.
If you are interested in what is the Gradle wrapper and why it’s helpful to have, read the section below.
When you setup a project in Android Studio, it automatically generates several files for you that help to allow people to build your code without needing to install Gradle ahead of time, which is useful especially when needing to do continuous integration testing.
By checking in the gradlew and gradlew.bat files into your source code repository, other people on Unix and Windows platforms do not need to go through the process of manually downloading Gradle or installing Android Studio.
The gradle-wrapper.properties file, which is created when you first create an Android Studio project, determines what version of Gradle to use:
If you wish to upgrade Gradle versions, you need to update the distributionUrl accordingly in gradle-wrapper.properties :
You can check this link to find the latest version. Note that the Gradle releases are independent of the Android Gradle plugin, which is defined in your build.gradle config.
Gradle will use this configuration to see if the version has already been installed. If not, it will be downloaded and stored in a separate directory. (For Unix machines, the various Gradle downloads will live in
In addition, you will need to setup the Android Gradle plugin by setting your build.gradle to have a dependency:
If you are using the android-apt plugin, Gradle v2.3.0 now supports the annotationProcessor syntax natively. See here for migration details. Basically, the process involves:
- Remove the android-apt plugin from your build scripts
- Change all apt, androidTestApt and testApt dependencies to annotationProcessor , androidTestAnnotationProcessor , and testAnnotationProcessor respectively.
Google maintains the Android Gradle plugin and you can find the latest version at http://tools.android.com/tech-docs/new-build-system. Both Gradle and the Android Studio plugin are constantly evolving, so you check the site to see what versions of Gradle are supported for which plugin.
Also, keep in mind that the Android Gradle plugin finds your SDK by what is defined in the local.properties file. You should already find this local.properties file in your project directory:
If you don’t want to set local.properties, you can also define the ANDROID_HOME environment variable which points to your Android SDK.
Once your Gradle wrapper is set up, you can use its androidDependencies command to generate a diagram of your app’s dependencies on the SDK and support SDK, broken out by each library that you use.
Finally, you can check your working installation by running:
If you are using Windows, you will be using gradlew.bat instead.
To build the APK, run this command in the root directory of your project:
If a build occurs and you see the output:
Then Gradle is successfully set up for your project. If you get an error, try googling the error. Usually, the issue is that you need to install the build tools.
If you have integration tests you want to run, make sure you have an open emulator or connected device and run this command in the root directory:
This will build the APK, then automatically compile and run your integration tests.
If you want to delete old APKs before you re-run either ./gradlew (build without tests) or ./gradlew build (build with tests), run:
To add dependencies to your project, you need to modify the build.gradle file and add extra lines configuring the packages you require. For example, for certain Google or Android, dependencies look like:
You can also add dependencies based on the Maven Central Repository. The best tool for finding packages is actually the Gradle Please utility that takes care of helping you locate the correct package and version to add to your gradle file for any library:
If you are planning to setup your own project without Android Studio (i.e. via Eclipse), the current recommendation is to setup the Gradle wrapper (http://www.gradle.org/docs/current/userguide/gradle_wrapper.html). The reason is that other people trying to use your project do not need to install Gradle themselves once you’ve generated the files needed to bootstrap the process.
To generate this initial set of files (Android Studio will automatically handle this work for you), you need to add these lines to your build.gradle file:
The files below will be generated. Similarly, Android Studio will create the same directory structure when the «wrapper» option is used :
Normally most dependencies can be retrieved remotely from a Maven or Gradle repository hosted at Maven Central or BinTray. If you wish to include a local dependency, you can copy the source to the project’s root directory. For instance, suppose you wanted to fork a copy of the material intro repository. You could copy this source into your main project as follows:
You need to modify the settings.gradle file to specify that what projects are available. Note that this new directory prefixed with a «:» operator:
Next, go to your app/build.gradle and make sure to specify the compile project(‘:material-intro:’) is included:
For more information, see the documentation about multi-project builds.
There are several configuration tweaks that can be experimented with to significantly speed up gradle build times. In Android Studio, open the gradle.properties file in the project and add:
On average, this will cause a 65% decrease in your build times. A few additional resources are included below:
Gradle provides enormous flexibility in enabling you to customize your builds for paid/unpaid versions, debug/production releases, and use different signing keys. Take a look at this guide for more information.
Check out the following links for more details:
Источник