- Checkout and build the source code
- Doing a checkout
- Building
- Check out a specific release
- Build Android Studio Source Code
- Run Bazel
- Install prerequisites for Windows users
- Build Android Studio using IntelliJ
- Building from the command line
- Common issues
- Build android from source code
- Загрузка и сборка AOSP
- Загружаем AOSP
- Сборка
- Готовим IDE для отладки
- Запускаем отладку
Checkout and build the source code
Like the Android operating system, Android Studio is open source and free of charge to all. Android releases source code to the Android Open Source Project (AOSP) after each stable release, described in detail here.
As of Android Studio 1.4, Android Studio is aligned to the same model of releasing source code after each stable release. For those who contribute to Android Studio, the code contribution process is the same as the Android platform.
Please continue to submit patches to the Android Studio AOSP branch.
We will do code-reviews and merge changes into subsequent versions of Android Studio. We’re incredibly grateful to all of you in the community for your collaboration and hard work on Android Studio.
Doing a checkout
Download an install the repo tool to checkout the source of Android Studio.
Check out the latest published source code using the following commands in a shell:
You can call the top level directory whatever you want. Those of us who check out multiple branches prefer to name the directories after the branches.
During the repo init command, it will ask you for your name and e-mail address which will be used by git if you commit changes and will be shown if you upload them for review.
To fetch the latest changes re-run the repo sync -c -j4 -q command.
-j , The number of parallel sync threads to start.
For your first sync, during which your client will be pulling down everything, we recommend a low value such as -j4 . For incremental syncs you can increase it as most fetch operations will be no-ops. However, specifying too high a number may decrease performance on machines with slow disks or slow internet connections.
-c , Syncs only the current branch to reduce sync time and disk space.
This means you will not be able to cherry-pick changes from branches you didn’t sync.
-q , Quiet. The normal output is fairly verbose.
See https://source.android.com/source/using-repo for more information about how to use repo.
Building
To build Android Studio, see Building Android Studio
To build the Android Gradle plugin, see Building the Android Gradle Plugin.
The parts of the SDK that can be built with the studio-* branches are only the IDE components and the SDK Tools. Each component is built differently due to varying build systems.
None of them use the make-based build system of the platform.
Historically, building the Android tools required building the full Android SDK as well. However, we’ve been gradually migrating the tools source code over to a more independent setup, and you can now build the Android Studio IDE without a full Android checkout and without a C compiler etc.
Check out a specific release
Releases since Android Studio 2.4 are tagged in git. This means you can use the tag to get the source code for a specific version. The tags are of this form:
For instance you can do a checkout of version 2.3.0 of the Gradle plugin with the following command:
Releases before studio-1.4 were developed in AOSP in the following branches
development branch | release branch | IntelliJ | Notes |
---|---|---|---|
studio-1.0-dev | studio-1.0-release | idea13-dev | This was the branch for 1.0 work |
studio-1.1-dev | studio-1.1-release | idea13-1.1-dev | This was the branch for 1.1 work |
studio-1.2-dev | studio-1.2-release | idea14-1.2-dev | This was the branch for 1.2 work |
studio-1.3-dev | studio-1.3-release | idea14-1.3-dev | This was the branch for 1.3 work |
Android Studio does not use the master branch. The branches ub-tools-idea133 and ub-tools-master are deprecated.
Источник
Build Android Studio Source Code
If you haven’t already done so, download the Android Studio source code so that you have a local copy of the following projects:
- Android plugin source code: /tools/adt/idea
- IntelliJ IDE base: /tools/idea/
- Shared library dependencies: /tools/base/ .
To learn how to build the Android plugin for Gradle from source, read The Android Gradle plugin.
Run Bazel
In order to successfully build Android Studio from source, you’ll need to make sure that you’re able to run the revision-controlled executable of Bazel that’s located in the /tools/base/bazel/ directory:
To make sure Bazel can execute Android Studio build tasks, try running the following command:
To learn more about running Bazel (including running tests), read Building Studio with Bazel.
Install prerequisites for Windows users
If you’re on Windows, you need to complete the following steps before you build AS from the command-line:
Install Python 2.7 or higher: Ensure you have Python installed on your windows machine, and the path to python.exe is added to your PATH environment variable. Note: It is recommend you use the 64-bit version, although the 32-bit version should work fine.
Install msys2: When building Android Studio, Bazel expects to find msys2 installed at c:\tools\msys2\ . Otherwise, you get a build error.
Install Visual Studio 2015 build tools: Otherwise, you get a build error.
Install Git for Windows: If you haven’t already done so, download and install Git for Windows (64-bit):
- Enable the option to Use Git from the Windows Command Prompt.
- Enable the option to Checkout Windows-style, commit Unix-style line endings.
- Add Git for Windows to your PATH environment variable.
- Configure Git to support long paths (that is, paths longer than 260 characters):
- Set the following PATH environment variables:
Download and install git-repo and include it in your PATH environment variable.
Download the Android SDK. You can do this in one of two ways:
- Use the SDK Manager from a pre-installed version of Android Studio.
- Download the SDK command line tools, and then use the sdkmanager command line tool to download an Android SDK package.
Build Android Studio using IntelliJ
If you are interested in making changes to the Android Studio codebase and building the IDE from source, you can do so using IntelliJ. To begin, you need to first configure a new project from the Android Studio source code, as follows:
- Download and install the latest version of IntelliJ IDEA Community Edition.
- Open IntelliJ IDEA and create a new project.
- When prompted to select the source directory for your project, select /tools/idea/ and click OK.
- Keep clicking Next until you are prompted to select the project SDK.
- Point IntelliJ to your local JDK, as follows:
- Select IDEA jdk from the left pane.
- While IDEA jdk is highlighted, click Add new SDK (+) > JDK. Note: The SDK you add should be a standard JDK, NOT an “IntelliJ Platform Plugin SDK”.
- Navigate to where you downloaded the Android source code and select the JDK package included in prebuilts/studio/jdk/
- If you are on Linux or Windows, also add /lib/tools.jar to the IDEA jdk classpath.
- Keep clicking Next until IntelliJ creates your project.
- After the IntelliJ finishes creating your project, click Build > Rebuild Project from the menu bar.
- If you see issues compiling .kt files, make sure that you’ve installed the Kotlin plugin
- Select AndroidStudio from the Configurations pulldown menu near the top right of the IDE.
Note: If you run into issues compiling *.groovy files, make sure you enable the Groovy plugin.
To build Android Studio, click the Run button (which looks like a green ‘play’ button) near the top right corner of the IDE.
Building from the command line
To build Android Studio from the command line, run the bash shell as Administrator and execute the following commands:
Windows users: to build Android Studio from the command line from a Windows machine, run Command Prompt as Administrator and execute the following commands:
You should find compressed build artifacts in studio-master-dev/out/artifacts/ . To run the version of Android Studio you just built, extract the artifact for your OS, and then run either /bin/studio.sh or \bin\studio.exe from the extracted directory.
Common issues
Error: java: package com.sun.source.tree does not exist: Make sure to add tools.jar to the “IDEA jdk” configuration, as explained above in Build Android Studio using IntelliJ.
java.lang.UnsatisfiedLinkError: C:\cygwin64\home. \tools\idea\bin\win\jumplistbridge64.dll: Access is denied: You may get this exception if you are trying to load and run the IDE project on Windows using Cygwin. To fix this issue, grant execute permissions to necessary files by opening a command prompt as Administrator and running the following command:
Alternatively, you can navigate to the tools\bin\win\ directory and perform the following actions for each .exe and .dll file:
- Right-click on a file.
- Select Properties to open a dialog.
- Click on the Security tab.
- Click Edit.
- Enable execute permission.
- Click OK.
Источник
Build android from source code
Инструкции по сборке Android из исходников
Мануалы в помощь новичку и обсуждение для гуру!
Описание | Старая шапка | Собираем ядро для MTK | Первая помощь | Редактирование системных ресурсов Android | Средство обработки прошивок
Что такое ADB и с чем его едят, читаем тут. Отследить новую версию ADB можно в репо от Google.
ADB для Winodws — Скачать sha1:52b4816990d2d18a34645bbf20a31b38a7859d4c
ADB для Linux — Скачать sha1:31078104e5927d823c28550c01275c437a87def7
ADB для MacOSx — Скачать sha1:1403fa0d1bb57ec31170d7905e8505e3b0ed05ee
Что такое маркет и с чем его едят, читайте в этой теме.
Android 4.1.*: microgapps скачать
Android 4.2.*: microgapps Скачать
Android 4.3.*: microgapps Скачать
Android 4.4 : ART microgapps Скачать
Android 4.4.1: ART microgapps Скачать
Android 4.4.2: ART microgapps Скачать
Android 5.0.2: ART microgapps Скачать
Android 5.0.2: ART microgapps Скачать By Mansi
Android 5.1.0: ART minigapps Скачать faq
microgapps — пакет Google Apps с самым основным, только Google Play и framework. Остальное можно установить из Google Play.
minigapps — Пакет Google Apps с самым основным набором ПО от Google.
ART — совместимы с ART режимом, появился в версиях Android 4.4 KitKat.
FlymeOS 5/6 от rocker123
Скачать Огромная коллекция на XDA 4.x-6.x
Скачать OmniRom + Prebuilts 4.x-6.x От ctavropoholb
Скачать Qualcomm MSM8974 и MSM8939 От acdev
Скачать MIUI PatchRom miui5-7 От ctavropoholb
Скачать CyanogenMod 10.1 — 13 4.х.х-6.х.х От ctavropoholb
Скачать CyanogenMod 12.1 android-5.1.1_r18 От SteelBreaker
Скачать Prebuilts AOSP 5.0.x От assusdan
Скачать MIUI PatchRom KitKat v6 От vgdn1942
Скачать AOSP mirror repo От wladimir_tm
Скачать AOSP, AOKP, CM, MIUI 4.4.4 От vaibhavpandeyvpz
Скачать CyanogenMod 11 4.4.4 От Никита Pro Android
Скачать CyanogenMod 10 4.1 От Scorpio92666
Скачать CyanogenMod 7.2.0 2.3.x От pryanya96
Скачать AOSPA ParanoidAndroid 4.4.4 От mrAlmid
Скачать Ubuntu phablet 4.4.2_r1 От Каточимото
Скачать repo snapshots cm-10.2 — android5.1 От wladimir_tm
После чего, качаем исходники командой repo sync
Источник
Загрузка и сборка AOSP
Решил поделиться своей инструкцией как собрать AOSP (Android Open Source Project). Эта инструкция будет полезна тем кто хочет посмотреть что-же внутри Android и возможно заняться системной разработкой. В любом случаи эти знания полезны для понимания самого Android, как раз для этого и решил собрать AOSP.
Проект собираю на elementary 5.1 OS Ubuntu 18.04 LTS (bionic), пытался на MacOS собрать, но так и не удалось. Для исходников и сборки нужно 200 Гб на жестком диске (лучше SSD, на обычном производительность сильно проседает). Так же много времени, я потратил чтобы скачать и собрать около 20 часов, частично виновата «слабая» конфигурация моего компьютера. У меня установлено всего 8 Гб оперативной памяти, но увеличил размер swap-а до 16 Гб.
Загружаем AOSP
Установить требуемые пакеты для загрузки и сборки :
Создаем папку и качаем repo утилиту для загрузки исходного кода
Исходники AOSP состоят из отдельных проектов с собственными git-репозиториями, repo позволяет упросить всю загрузку всех проектов и разложить по нужным папкам.
- -u — урл git-репозитория с манифестом
- -b — ветка (самая последняя на текущий момент)
- —depth — скачивать только одну ветку (если не использовать, то для каждого репозитория скачается весь индекс, что увеличит время загрузки и место на диске)
Выбрал самую последнюю версию Android 10. Не использую develop или master, так как там устаревший манифест и проект скорее не соберется.
Теперь можно запустить загрузку исходников AOSP
- -c — скачивать только текущую ветку манифеста (как указал выше — android-10.0.0_r45)
- -j — количество потоков, обычно указывается столько доступно процессоров
- —no-tags — не скачивать тэги с репозитариев
- —no-clone-bundle — не пытаться качать clone.bundle (упакованная репа, которая уменьшить время на загрузку, но не у всех сервер формирует этот bundle),
—no-clone-bundle можно попробовать убрать, что в теории ускорит скачивание, но у меня заваливается с 404 ошибкой
Скачивание может занять минуты и часы, теперь с repo закончили, если нужно почитать больше то ищите в официальной документации: https://source.android.com/setup/develop/repo
Сборка
Настраиваем среду разработчика:
x86_64 — указывается под какой девайс собирать, в данном случае Generic x86_64 подходит для эмуляторов, если будете запускать на Nexus девайсах, то ищите детали в документации https://source.android.com/setup/build/building#choose-a-target
eng — тип сборки (сокращение от engineering), с максимальными логами и дополнительными утилитами для отладки. Другие тип сборки думаю не особо интересны
Для сборки java файлов увеличиваем Heap size, если этого не сделать, то сборка всего завалится с StackOverflow ошибкой:
Так же можно добавить в .bashrc чтобы постоянно не повторять команду
Все, теперь готовы к сборке:
Можно не использовать CCACHE, что уменьшит количество занимаемого места на диске, но увеличит время повторной сборки. На моем «слабом» компьютере сборка заняла где-то 16 часов.
После окончания сборки, запускаем эмулятор:
-show-kernel — выводить уведомления в консоль
Если нажать Enter, то попадем в консоль эмулятора
Если эмулятор не запустился, нужно будет проверить что включена виртуализация
Готовим IDE для отладки
Для начала необходимо сгенериовать проект для IDE, проект генерируется для IDEA. Собираем модули для генератора:
Чтобы весь AOSP затолкать в проект, то просто запускаем генератор
Но сгенерированный IDEA проект будет очень «тяжелым». Одно открытие и индексация занимает достаточно много времени. Лучше генерировать IDEA проект для каждого отдельного проекта, например для Android фреймворка
Весь список доступных проектов можно посмотреть в
Открываем сгенерированный base.iml (находится в папке frameworks/base) в IDEA. Дальше нужно настроить Java, только нужно подключать java без библиотек, так как у AOSP-а свои реализации.
Запускаем отладку
Для начала необходимо запустить monitor
возможно потребуется дополнительно поставить jre
sudo apt install openjdk-8-jre-headless
Выбираем процесс, который будем отлаживать. В monitor-е выбираем процесс и справа от порта процесса появится /8700, это как раз порт отладчика, к нему можно подключаться через IDEA.
Все системные штуки находятся в system_process. Его мы и будем отлаживать.
monitor один самых полезных инструментов при отладке и исследования работы AOSP
В проекте добавляем новую Remote конфигурацию, только указываем 8700 порт. Именно к этому порту и будем подключаться
Запускаем Debug (Run → Debug)
Чтобы удостоверится, что все подключилось поставьте брейкпоинт в frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java файле на метод:
и запустить любое приложение на эмуляторе (например, Settings).
Источник