- How to Build a Custom ROM from Android Open Source Project
- Requirements for this Guide:
- Setting Up Your Build Environment
- Downloading the Android Source
- Most Popular Custom ROMs for Android: LineageOS, Pixel Experience, Paranoid Android, and more!
- LineageOS
- Pixel Experience
- Paranoid Android
- Evolution X
- ArrowOS
- dotOS
- Honorable mentions
- Another honorable mention: Xiaomi.EU
- Загрузка и сборка AOSP
- Загружаем AOSP
- Сборка
- Готовим IDE для отладки
- Запускаем отладку
How to Build a Custom ROM from Android Open Source Project
If you’re familiar with rooting your Android phone or downloading custom ROMs, such as the highly popular CyanogenMod or its successor Lineage OS, you may have wondered – how do people build these ROMs? How much work exactly goes into developing a customized ROM?
This guide will walk you through the basics of developing your own custom Android ROM. It should be noted that this is a massive undertaking – if you have zero experience in coding or fooling around in Linux terminals, you may want to get some knowledge under your belt before diving into this deep-end. But if you have at least a basic idea of those things, I will try to explain things as simply as possible, so you can follow along.
Basically what we’re doing is downloading the raw Android source code (AOSP) and modifying it to our liking. Because there are so many sources to choose from for different devices, this guide will simply reference the master source known as AOSP (Android Open Source Project).
Now the thing about the AOSP is that the pure source code does not include device-specific hardware proprieties. In layman’s terms, hardware like your camera and GPU will not work “out of the box” when developing with the AOSP. In fact, your device will not even boot without these hardware binaries.
If you’re developing for a Google-branded phone (Pixel, Nexus, etc) you can find the hardware binaries directly from Google, and this guide will walk you through obtaining and building them into your ROM. However, if you’re developing a ROM for a brand-name phone (Sony, Samsung, etc)… well, bless your heart, because you’re in for a ride.
Some manufacturers have their own open-source projects or release development tools for would-be developers, whereas other manufacturers keep a tight lid on their proprietary codes. Here’s a brief list of open-source projects from the more popular manufacturers:
With that out of the way, let’s continue under the assumption we are building a ROM for the most basic, vanilla Android experience, for a Google Pixel device. With this knowledge under your belt, you’ll be able to branch out on your own and start developing customized versions of specific manufacturer’s ROMs.
Requirements for this Guide:
- Android Open Source Project
- Pixel XL phone or an Android emulator for Linux
- 64-bit Linux Operating System – Ubuntu or Linux Mint are the most newbie-friendly distros, whereas BBQLinux was developed specifically with Android developers in mind.
- Python
- A beefy computer (compiling code takes a lot of memory and space!)
Setting Up Your Build Environment
Let’s begin by setting up the Android emulator on your Linux machine. Whether or not you have a Google Pixel XL device, it’s always safest to try your new ROM on an Android emulator before flashing it to your device. My personal favorite is Genymotion, so I’ll walk you through installing that particular emulator. However, you can also check out this guide “Best Android Emulators”, as most of them also have Linux compatibility.
Head over to the Genymotion website, register an account, verify it through email, and download the executable to your Linux desktop.
Now open a Linux terminal, and type:
Chmod +x genymotion-xxxxx.bin (replace xxxx with the version number in the filename)
./genymotion-xxxxxx.bin
Press Y to create the Genymotion directory. Now type in the terminal:
cd genymotion && ./genymotion
Now it will ask you to begin the installation process, so just keep clicking Next until you get to the Add Virtual Devices window. Select “Pixel XL” under Device Model option, and then complete the installation. You can test the virtual device out if you want, it will basically be like having a Pixel XL phone on your desktop.
Let’s now set up Python:
$ apt-get install python
Now we need to setup the Java Development Kit on your Linux machine. Open the Linux terminal and type the following commands:
$ sudo apt-get update
$ sudo apt-get install openjdk-8-jdk
Now you will need to configure the Linux system to allow USB device access. Run the following code in the Linux terminal:
This will download the required 51-android.txt file that allows the aforementioned USB device access. Open the .txt file and modify it to include your Linux username, then place the .txt file in the following location: (as the root user). Now plug your device into your computer via USB for the new rules to automatically take effect.
Downloading the Android Source
The AOSP is hosted on Git, so we’re going to use a tool called Repo to communicate with Git.
First we need to setup a /bin folder in your Home directory. Type the following commands into the Linux terminal:
Now we will download the Repo tool, so type into the Linux terminal:
/bin/repo
$ chmod a+x
After Repo is installed, we must now create an empty directory to hold your work files. So type this into the Linux terminal:
$ mkdir WORKING_DIRECTORY
$ cd WORKING_DIRECTORY
Now we’ll configure Git with your name and email address – use a Gmail address that you check regularly, otherwise you will not be able to use the Gerrit code-review tool.
$ git config –global user.name “Your Name”
$ git config –global user.email you@gmail.com
Now we’ll tell Repo to pull the latest master manifest of AOSP from Git:
If done successfully, you’ll receive a message that Repo has been initialized in your working directory. You’ll also find a “.repo” directory inside the client directory. So now we’ll download the Android source tree with:
Building the Android Source
This is where the hardware binaries mentioned at the beginning of this guide come into play. Let’s head over to the AOSP drivers page and download the Pixel XL binaries for Android 7.1.0 (NDE63P). You want to download both the vendor image and the hardware components. These come as compressed archives, so extract them to your desktop and run the self-extracting script from the root folder. Choose to install the binaries to the root of the WORKING_DIRECTORY we created earlier.
Now type into your Linux terminal:
$ make clobber
$ source build/envsetup.sh
Now we’ll choose the target to build, so type:
$ lunch aosp_marlin-userdebug
$ setpaths
$ make –j4
There, we have now “built” an Android ROM from source. So let’s test it in the emulator, by typing into the terminal:
So play around in the emulator a bit. As you can see, a purely vanilla Android experience is quite minimal, and this is why manufacturers customize the AOSP to their needs. So you could flash this ROM we just built to your device if you wanted, but without adding any enhancements, a purely vanilla Android experience would be a very boring thing indeed.
So what manufacturers will typically do with the AOSP is fork it, add their own proprietary binaries, customize the UI, add a boot logo, etc. Manufacturer’s basically just paint over the stock Android ROM, and so that will be your next goal as well.
Stay tuned, as the second part of this guide will go through adding fonts, themes, and a boot animation to your ROM!
Источник
Most Popular Custom ROMs for Android: LineageOS, Pixel Experience, Paranoid Android, and more!
If you have been following the Android aftermarket development scene for a while, you must have heard of the term custom ROM. A custom ROM is essentially a third-party operating system that replaces the factory-installed stock ROM or skin on your phone. Even though manufacturers like Samsung, OnePlus, and Xiaomi have done a great job of refining their Android skins, there’s still plenty of interest in custom ROM development for plenty of devices.
As soon as Google drops the source code of a new version to the Android Open Source Project (AOSP), the modding community starts working toward making the latest flavor of Android accessible to more and more devices in the form of custom ROMs. As such, there are a number of Android custom ROM distributions to choose from. If you’re itching to try out the vanilla Android experience on your shiny new Android phone or just want to breathe new life into an old device stored in your closet, but unable to pick the perfect candidate, then this guide is for you. Below you can find the most popular custom ROMs in the domain of Android.
LineageOS
Truth be told, the LineageOS project doesn’t really need an introduction at this point. Being the true successor to the legendary CyanogenMod project, LineageOS is a lightweight ROM with the bare minimum in additional features, resulting in a high-performance, high versatility Android variant one can imagine. The official LineageOS builds are standardized against a Device Support Requirements charter, which ensures that all the basic hardware functionalities (such as Wi-Fi, Bluetooth, GPS, Camera, NFC, etc.) continue to operate after replacing the factory-installed software with LineageOS.
No wonder the XDA community loves LineageOS to the moon and back, because it has set itself as the highest benchmark in the world of custom ROMs.
Pixel Experience
If you’re a stock Android enthusiast and want to experience vanilla Android just like on Google’s own Pixel devices, then you should definitely check out the Pixel Experience project. The custom ROM comes with all Google apps and Pixel goodies, like the launcher, wallpapers, icons, font, and boot animation out of the box.
The developers also offer a “Plus” variant of the ROM which features a handful of extra customization options that aren’t present in the basic distribution.
Paranoid Android
Like LineageOS, the Paranoid Android project (also known as AOSPA) has a rich heritage. It was once a top contender in the Android ROM scene for many different reasons — innovative features, a slick user interface, a revolutionary camera app, you name it. If you’re a fan of the stock Android look, but do admire aesthetics over random customization options, then I would highly recommend taking this custom ROM for a spin.
Evolution X
Are you a vanilla Android enthusiast and looking for a Pixel-esque ROM that also offers some useful UI/UX customizations? Take a look at the Evolution X project. The ROM comes with preinstalled Google apps and Pixel goodies, and features several customizations like Status Bar visibility toggle and Gaming Mode Quick Settings Tile.
ArrowOS
The ArrowOS project started with the sole aim of keeping things simple, clean, and neat. The developers added only a handful of tweaks on top of AOSP, aiming to deliver smooth performance with better battery life. The end result is a lightweight ROM that offers comparatively better performance and reliability over the stock Android.
dotOS
For those not familiar with dotOS, it stands for “DroidOnTime” and is based on AOSP. However, unlike other AOSP-derived ROMs, dotOS is known for its unique user interface and innovative features. In a nutshell, if you want a stock Android experience with a host of additional features, opt for dotOS.
Honorable mentions
Additionally, distributions like OmniROM and BlissRoms have introduced a plethora of novel concepts to the custom ROM scene that are later being adopted by many other ROM maintainers. Enthusiastic users will also find out several other custom ROM projects such as Potato Open Sauce Project (POSP), PixysOS, RevengeOS, Havoc-OS, crDroid, and more on our forums, as the developers continue to come up with something new all the time.
Another honorable mention: Xiaomi.EU
For those of you with a Xiaomi, Redmi, or POCO device, and who just want to get rid of the bloatware and advertisements of the MIUI skin, you can go for the Xiaomi.EU ROM. This particular distribution is not an actual custom ROM in the truest sense of the term, but the extensive modifications make it quite an equivalent one in the MIUI ecosystem.
The daily builds of the ROM are based on Chinese MIUI beta firmware packages and have further been localized for the international markets. As a result, users can get their hands on all the bleeding edge functionalities introduced in the Chinese variant of MIUI before Xiaomi officially ports them to the global ROM.
Now you’re aware of the most popular custom ROMs in the scene, pick one for your device and give it a go. In case you need any help before or during installation, don’t forget to take a look at our excellent guide to installing a custom ROM on your Android Phone. And once you have the ROM installed, see if you can further upgrade your Android camera experience with GCam.
Источник
Загрузка и сборка 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).
Источник