How to build android rom

Сборка собственной Android-прошивки, часть 1/3

Оригинал: How to build Android ROM Part 1/3
Автор: Masc
Дата публикации: 6 марта 2017 г.
Перевод: А.Панин
Дата перевода: 28 марта 2017 г.

Разработка Android-прошивок — настройка рабочего окружения

Нередко мобильные устройства поставляются с неоптимизированными прошивками от производителя, которые после непродолжительного использования начинают работать медленно и нестабильно. Многие сталкивающиеся с таким поведением прошивок люди ищут стандартные решения в сети, при этом некоторые из них собирают собственные прошивки для своих устройств.

Это первая из трех статей серии, в которой я постараюсь описать максимально понятным языком процесс самостоятельной сборки Android-прошивки для вашего устройства.

Если вы хотите собирать Android-прошивки, вам понадобится установленный на компьютере Linux-дистрибутив, ну а если вы не можете выделить отдельный компьютер для этих целей, вы вполне можете обойтись виртуальной машиной с Linux-системой.

Я буду использовать дружелюбную систему Ubuntu 16.04, что рекомендую и вам.

Требования

  • Дистрибутив Linux
  • Как минимум 200 ГБ свободного пространства на жестком диске или твердотельном накопителе
  • Мощный компьютер с как минимум 4 ГБ оперативной памяти и производительным четырехядерным центральным процессором
  • Качественное соединение с сетью Интернет на скорости как минимум 600 КБ/с

Если у вас есть все необходимое, можно начинать работу.

Все приведенные в данной статье команды должны исполняться с помощью приложения Терминал и, разумеется, я не буду повторять это после каждой команды.

Если в вашей системе не установлена виртуальная машина Java, вы можете выполнить следующую команду для ее установки вместе со всеми библиотеками:

Сборочный инструментарий

Выполните следующую команду для установки сборочного инструментария (ее исполнение может занять достаточно много времени в зависимости от скорости вашего Интернет-соединения):

Не догадываетесь, что это такое? Ну, это важный инструмент, необходимый для соединения с серверами и загрузки исходных кодов, которые понадобятся впоследствии. Его название происходит от слова «репозиторий», обозначающего централизованное хранилище определенных ресурсов. В нашем случае в этом хранилище хранятся исходные коды всех программных компонентов, которые будут компилироваться и добавляться в создаваемую прошивку.

Выполните следующую команду для для установки описанного инструмента в свою систему:

CCACHE

Это полезная утилита, которая используется для кэширования бинарных файлов и позволяет сократить время компиляции (примерно на 50%).

Для ее инициализации следует выполнить следующую команду:

Разумеется, вместо приведенного значения вы должны указать количество свободных гигабайт на своем жестком диске.

Для ознакомления с статистикой кэширования следует использовать следующую команду:

Для удаления файлов кэша — следующую команду:

Настройка рабочего окружения почти закончена — осталось открыть файл bash.rc:

Теперь следует перейти к последней строке этого файла и вставить в него следующие строки:

Наконец, следует закрыть текстовый редактор и выполнить следующую команду для применения изменений:

Пришло время перезагрузить систему.

А это две следующие статьи серии, описывающие процесс сборки прошивки!

Источник

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.

Читайте также:  Samsung galaxy a51 версия андроид

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:

Читайте также:  Android sdk описание пакетов

/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!

Источник

[GUIDE]How To Build A ROM Using A Phone

Saurabhcr7

Senior Member

I am writing this tutorial together in an attempt to help beginners which are trying to build a ROM from source for the first time.I faced many problems when I started building roms, so I thought it will be better to help someone who is trying the same thing.I have tried to make this guide easy to understand.Please feel free to PM if you have any doubts!!
And if you built a rom by following this guide then please press the thanks button, it will motivate me.

1. Who do not have a PC which meets required requiements for building a rom
2. Who cannot download the sources which might be upto 10GB
3. Who is building a rom for the first time

Prerequisites
1. Android Phone
2. A decent internet connection
3. A debit/credit card
4. Brain

Contents
1. Making a Google Cloud Account
2. Setting up the VM (Virtual Machine) on your phone
3. Setting up the build environment
4. Initializing and syncing the repo
5. Cloning the device,kernel and vendor tree
6. Building the rom
7. Uploading the ROM in Google Drive

1. Making A Google Cloud Account ​

NOTE: You will need a credit/debit card for making an account and it is free to use Google Cloud for one year only.

STEP 1:Open Google Cloud from here.
STEP 2:Click on Free Trial

2. Setting up the VM (Virtual Machine) on your phone

STEP 1:Download Juice SSH app from here.
STEP 2:Open Juice SSH app and click on «Connections».
STEP 3:Navigate to «Identities» and create a new identity by pressing the «+» button.
STEP 4:Input the «Nickname»,»Username» (You can enter your name also in both places) and then click on «Private Key»(Set (Optional) button). Navigate to «Generate» and press OK and click on the tick icon.
STEP 5:Now long press the identity you just created and click on «Export Public Key» and click on ES Note Editor or Keep (You need any one of them) and replace the «JuiceSSH» written at the end with your username you entered in the identity and now copy the whole text.
STEP 6:Open Google Cloud and navigate to Computer Engine->Metadata->SSH Keys. Click on edit and then add item.Paste the text you just copied and save it.
STEP 7:Navigate to Computer Engine->VM Instances. Click on «Create Instance».Enter the name(Any name).Select Machine Type as «4vCPU». Select Boot Disk as «Ubuntu 16.04 LTS» and set the size to 1000GB.Tick both «Allow HTTP traffic» and
«Allow HTTPS traffic» and click on create.
STEP 8:Now it will take a minute.After it is created copy the External IP.
STEP 9:Now open Juice SSH app and navigate to «Connections» and create a connection by clicking on the «+» icon.Input the nickcname you entered while creating the identity.Paste the External IP in the «Address» column and click on the tick icon.
STEP 10:Now click on the connection you just created. This will open the terminal on which you need to work.

Читайте также:  Safe exam browser для android

3. Setting up the build environment
NOTE: You just need to copy and paste the below codes one by one.

1. sudo apt update
2. sudo apt upgrade
3. sudo apt-get install git-core
4. git clone https://github.com/akhilnarang/scripts
5. cd scripts
6. bash setup/ubuntu1604linuxmint18.sh
7. mkdir -p

/android/lineage (Replace lineage with your rom name or you can also use lineage for any rom for easy to understand))
9. curl https://storage.googleapis.com/git-repo-downloads/repo >

/bin/repo
10. chmod a+x

/android/lineage

4. Initializing and syncing the repo
1. repo init -u https://github.com/LineageOS/android.git -b cm-14.1

NOTE: Here I am compiling lineage os 14.1 therefore I am using it’s repo initializing command.
You can find repo initialization command for your rom by the following method:
(i) Google search «rom_name github» (Replace rom_name with your rom name)
(ii) Open the rom github in dextop mode.(Use Google Chrome)
(iii)Click on the «manifest» or «android_manifest»
(iv) Select the branch which you want to build and copy the repo initialization command given at bottom.

Go get a coffee till the source is syncinc. It will take time depending on your internet speed.

5. Cloning the device,kernel and vendor tree

1. git clone device_tree_link_here -b branch_name_here device/manufacturer_name_here/device_name_here
Eg: git clone https://github.com/LineageOS/android_device_xiaomi_mido.git -b cm-14.1 device/xiaomi/mido
2. git clone kernel_tree_link_here -b branch_name_here kernel/manufacturer_name_here/chipset_name_here
Eg: git clone https://github.com/LineageOS/android_kernel_xiaomi_msm8953.git -b cm-14.1 kernel/xiaomi/msm8953
3. git clone vendor_tree_link_here vendor/manufacturer_name_here
Eg: git clone https://github.com/TheMuppets/proprietary_vendor_xiaomi.git vendor/xiaomi

NOTE: 1.To find device tree link follow the following steps:
(i)Google search «Device_name device tree github»
(ii)Select the branch and copy the device tree link.

2.To find the kernel tree link follow the below steps:
(i)Google search «lineage os github».
(ii)Input your chipset name in the search box and select the repository for your device.
(iii)Copy the link.

3.To find the vendor tree link follow the below steps:
(i)Google search «The Muppets Github».
(ii)Find the repository for your device and copy the link.

If you can’t find any tree with the above methods, then simply google search that tree for your device.

1. export USE_CCACHE=1
2. prebuilts/misc/linux-x86/ccache/ccache -M 50G
3. export CCACHE_COMPRESS=1
4. . build/envsetup.sh
5. brunch device_name_here
or
5. make bacon -j8

Now it will take approx 7-8 hrs or more depending upon your internet speed.Go get a sleep till then.

7. Uploading the ROM in Google Drive

Источник

Оцените статью