Make android from source

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):

  1. Enable the option to Use Git from the Windows Command Prompt.
  2. Enable the option to Checkout Windows-style, commit Unix-style line endings.
  3. Add Git for Windows to your PATH environment variable.
  4. Configure Git to support long paths (that is, paths longer than 260 characters):
  5. 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:

  1. Use the SDK Manager from a pre-installed version of Android Studio.
  2. 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:

  1. Download and install the latest version of IntelliJ IDEA Community Edition.
  2. Open IntelliJ IDEA and create a new project.
  3. When prompted to select the source directory for your project, select /tools/idea/ and click OK.
  4. Keep clicking Next until you are prompted to select the project SDK.
  5. Point IntelliJ to your local JDK, as follows:
    1. Select IDEA jdk from the left pane.
    2. 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”.
    3. Navigate to where you downloaded the Android source code and select the JDK package included in prebuilts/studio/jdk/
    4. If you are on Linux or Windows, also add /lib/tools.jar to the IDEA jdk classpath.
  6. Keep clicking Next until IntelliJ creates your project.
  7. 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
  8. Select AndroidStudio from the Configurations pulldown menu near the top right of the IDE.
Читайте также:  Android не работает разблокировка

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:

  1. Right-click on a file.
  2. Select Properties to open a dialog.
  3. Click on the Security tab.
  4. Click Edit.
  5. Enable execute permission.
  6. Click OK.

Источник

Загрузка и сборка 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).

Источник

How to make Android apps without IDE from command line

Nov 26, 2017 · 5 min read

A HelloWorld without Android Studio

Update: I’ve made a new course that explain how you can avoid Android Studio and Gradle, but still use IntelliJ iDE:

How to do Android development faster without Gradle

IntelliJ IDE, but not Gradle

In this tutorial, I will show you how you can build/compile an APK (an A n droid app) from your java code using terminal (on Linux) without IDE or in other words without Android Studio. At the end, I will also show you a script to automate the process. In this example, I will use Android API 19 (4.4 Kitkat) to make a simple HelloWorld. I want to say that I will do this tutorial without android command which is deprecated.

1. Install Java

First, you need to install java, in my case, I install the headless version because I don’t use graphics (only command line):

2. Install all SDK tools

Then download the last SDK tools of Android which you can find here:

Download Android Studio and SDK Tools | Android Studio

Download the official Android IDE and developer tools to build apps for Android phones, tablets, wearables, TVs, and…

I recommend to unzip it in the /opt directory inside another directory that we will call “android-sdk”:

Now, we have to install platform tools (which contain ADB), an Android API and build tools.

In fact, if you are on Debian, you can avoid installing platform-tools package and only install ADB like that:

3. Code the application

In this example, I want to compile a simple HelloWorld. So, first, we need to make a project directory:

Then we have to make the files tree:

Читайте также:  Темы виджеты для android

If you use exernal libraries (.jar files), also make a folder for them:

You have an example here:

How to use JavaMail on Android (without Gradle)

Hello guys!

Make the file src/com/example/helloandroid/MainActivity.java and put that inside:

Make the strings.xml file in the res/values folder. It contains all the text that your application uses:

The activity_main.xml is a layout file which have to be in res/layout:

You also have to add the file AndroidManifest.xml at the root:

4. Build the code

Now, I recommend to store the project path in a variable:

First, we need generate the R.java file which is necessary for our code:

  • -m instructs aapt to create directories under the location specified by -J
  • -J specifies where the output goes. Saying -J src will create a file like src/com/example/helloandroid/R.java
  • -S specifies where is the res directory with the drawables, layouts, etc.
  • -I tells aapt where the android.jar is. You can find yours in a location like android-sdk/platforms/android-/android.jar

Now, we have to compile the .java files:

If you have use an external, add it the classpath:

The compiled .class files are in obj folder, but Android can’t read them. We have to translate them in a file called “classes.dex” which will be read by the dalvik Android runtime:

But if you use external libraries, do rather:

If you have the error UNEXPECTED TOP-LEVEL EXCEPTION , it can be because you use old build tools and DX try to translate java 1.7 rather than 1.8. To solve the problem, you have to specify 1.7 java version in the previous javac command:

The -source option specify the java version of your source files. Note that we can use previous versions of Java even we use OpenJDK 8 (or 1.8).

We can now put everything in an APK:

Be aware: until now, we used three AAPT commands, the first and the second one are similar but they don’t do the same. You have to copy the classes.dex file at the root of project like above! Otherwise, AAPT won’t put this file at right place in the APK archive (because an APK is like a .zip file).

The generated package can’t be installed by Android because it’s unaligned and unsigned.

If you want, you can check the content of the package like this:

5. Sign the package

To do so, we firstly create a new keystore with the command keytool given by Java:

Just answer the questions and put a password.

You can sign an APK like this:

Note that apksigner only exist since Build Tools 24.0.3.

6. Align the package

It’s as simple as that:

Alignment increase the performance of the application and may reduce memory use.

7. Test the application

To test the application, connect your smartphone with a USB cable and use ADB:

But before run this command, I recommend to run this one:

If there is an error during installation or running, you see it with that command.

Voila! Here’s the result:

8. Make a script

If you don’t want to run all these steps every time you would like to compile your app, make a script! Here’s mine:

Notes

  • You can remove “test” if you just want to compile without testing.
  • This script only compile and run the app on the phone. But I can also make a script to automatically generate a new project like this one. I think I have a good idea to do so, but I need to know if you are interested. If it’s the case, please leave a comment or send me an e-mail.
  • I can also complete the script for external libraries. Likewise, let me know if you want this.

If you have any questions, don’t hesitate to ask them below or by e-mail ;-)! EDIT: Well I’m very busy actually…

Источник

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