- Сборка Android под Mac OS X
- Вводная
- Решение
- Building Android O with a Mac
- My Environment
- Setup your Build Environment
- Creating a case-sensitive disk image
- Download AOSP source code
- Building ASOP source code
- Install new Android Build on Device
- Restore Android Image
- Rebuild a single package
- System UI
- Android Framework
- Signing Build
- Troubleshooting
- Can not find Mac SDK or Required minimum for the macosx platform
- Error: could not find jdk tools.jar
- Make error — already defined
- GC overhead limit exceeded
- Case-insensitive filesystem
- Fatal error file not found
- No space left on device
- Missing and no known rule to make it
- UNITY3D DEVS — SETTING UP YOUR MAC FOR ANDROID BUILDS
- Let’s do this:
- So do I need to do this every time?
Сборка Android под Mac OS X
Вводная
Для одного из проектов потребовалось заняться доработками оригинального кода Android для создания прошивки под специфичную железку. Версия для сборки была выбрана уже относительно старая — AOSP 4.0.4, но на ней базируется стабильная ветка кода от производителя железки, поэтому условие необходимое. Кроме разработки под Android я занимаюсь разработкой iOS приложений, соответственно работаю под Mac OS X и использую Xcode как одну из сред для разработки.
Основной проблемой в моем случае явилось то, что старые версии AOSP ни кем не отслеживаются и новые правки в сборочную систему не вносятся. Поэтому если сборка master’а особой сложности не представляет, то сборка предыдущих версий Android под более свежие версии MacOS требует исправления ряда проблем.
В моем случае рабочее окружение выглядит так:
- AOSP 4.0.4 r1.1 (а так же 4.0.3 и 4.1.1)
- Mac OS X 10.7.5
- Xcode 4.6.3 и command line tools
- GNU Make 3.81
Все основные моменты и сложности сборки AOSP хорошо описаны в официальной документации. Там же указано что для сборки ветки 4.0.x необходимы MacOS 10.5 или 10.6 и рекомендован Xcode 3.14, а в разделе «Known issues» указано что ветка 4.0.x не совместима с MacOS 10.7.
MacOS и Xcode я использую для разработки и откатываться на предыдущие версии крайне не хотелось. К тому же был чисто спортивный интерес разобраться со сборкой без какого-то кардинального изменения окружения.
Решение
Непосредственно все первоначальные шаги для сборки описаны в документации и были выполнены в соответствии с ней: создан case-sensitive disk image, установлены необходимые утилиты, скачан код Android. Далее была запущена сборка с профилем full-eng.
Ниже я привожу тексты ошибок из консоли и методы исправления. В зависимости от версии AOSP и вашего окружения они могут проявляться все или частично. Большинство решений можно найти в интернете, я привожу лишь краткое описание необходимых действий. Кроме AOSP 4.0.4 также были проверены версии 4.0.3 и 4.1.1. Чем новее версия, тем меньше встречалось ошибок, но первые 2 имели место везде. Отдельно стоит заметить что при внесении описанных изменений, эмулятор собирается корректно и я не встретил проблем с запуском эмулятора указанных в том же официальном «Known issues».
Запуск сборки для решения проблем с компилятором осуществляется командой приведенной ниже. Здесь важная часть CC=«gcc» CXX=«g++», остальными могут быть стандартные параметры в любом порядке и сочетании.
По ходу сборки, не считая описанного в документации, возникали следующие проблемы:
Ошибка 1
Исправление
Применить патч https://bugs.webkit.org/show_bug.cgi?id=92264. Патч ложится с небольшой ошибкой, из-за расхождения контекста, нужно посмотреть rej и удалить пару старых строк, которые не смог убрат патч. Применять патч в директории external/webkit/.
Важно
Во время линковки, на финальной стадии сборки, могут появиться ошибки типа:
В зависимости от того добавляли ли вы изменения в CSSParser. Здесь проявляется некая мистика линковщика (для 4.1.1 версии со сборкой с этими исправлениями таких проблем нет). Для устранения проблемы нужно в CSSParser внести какие-нибудь изменения (считываемые компилятором, т.е. не комментарии). Я менял определение этой функции с cssyyparse(void*) на cssyyparse(WebCore::CSSParser*) или наоборот. Далее запустить пересборку — все пройдет гладко с этого места.
Ошибка 2
Исправление
Перенести определение в файл external/srec/portable/include/PortExport.h из ветки master в нашу.
Ошибка 3
Исправление
Добавить библиотеку LOCAL_SDL_LDLIBS += /usr/lib/dylib1.o в /development/tools/emulator/opengl/tests/translator_tests/ для GLES_V2/Android.mk и GLES_CM/Android.mk.
Ошибка 4
Разное определение функции strnlen в системе и в локальных файлах. К сожалению для этой ошибки лог не записал, но суть будет понятна при упоминании функции strnlen.
Исправление
Добавить условие для функции strnlen в external/elfutils/config-compat-darwin.h:
Ошибка 5
Выбор версии SDK по версии Mac OS для сборки эмулятора. Аналогично предыдущей ошибке без лога, но упоминание эмулятора qemu в логе укажет сюда.
Исправление
Заменить условие для версии Mac OS external/qemu/Makefile.android:
И добавить подключение библиотек для MacOS:
Ошибка 6
Если у вас операционная система стоит на диске с case-sensitive file system, то может проявиться такая ошибка:
Источник
Building Android O with a Mac
Mar 26, 2018 · 6 min read
After spending several hours to analyse dozens of posts and articles to compile Android O MR1 AOSP, I decided to write a short manual to help you to build your AOSP effortlessly 😉
This article is based on Official Android documentation: https://source.android.com/setup/requirements
My Environment
- OS: macOS Sierra 10.12.5
- CPU: 2,9 GHz Intel Core i5 (influence the speed compilation)
- RAM: 8 GB 1867 MHz DDR3 (8GB minimum, recommended 16GB)
- Disk: 200GB free space (after AOSP sources downloaded — minimum 200GB)
- Device: Nexus 5X (bullhead)
Setup your Build Environment
- Install Xcode: https://developer.apple.com/xcode/
- Install Xcode command line tools with:
- Install Homebrew with:
- Install JDK with: https://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html
- Check your Java version:
- Install GIT with:
- Install Python with:
- Install Make with:
Creating a case-sensitive disk image
Case sensitive volume of 200GB with the following command line:
Install tools and libraries via MacPort
Install MacPorts: https://www.macports.org/install.php then type the following command line:
Then create and edit the .bash_profile file with the following code:
Download AOSP source code
To identify the right b ranch to download , check the Build number of the target device. In our case OPM5.171019.017 which isncorresponding to the branch android-8.1.0_r18.
Warning: when you choose a branch be sure that the branch support the targeted device!
Select the targeted AOSP version with the branch with -b parameter: android-8.1.0_r18
Building ASOP source code
Select the device target with lunch command, then build the sources with make command:
When the build process if finished you get the following message:
Install new Android Build on Device
Connect the Device in USB, enable the Developer Mode, then input the following command lines in you Terminal:
Restore Android Image
To restore an official Android Image please download the target Image and follow the instructions:
- Download Android Image: https://developers.google.com/android/images
- Unzip the archive
- Execute the following command lines:
Rebuild a single package
To rebuild a single package (example: Dialer App) instead of rebuild the entire baseline, use the following command lines:
The output APK path will be prompt by the console, or located at the following path:
How to install it
System UI
Build System UI only:
How to install it
Android Framework
- Build Framework JAR only: mmm framework/base/
- Build Framework Resources only: mmm framework/base/core/res/
How to install it
Signing Build
The standard Android build uses four keys, all of which reside in build/target/product/security :
- testkey: Generic default key for packages that do not otherwise specify a key.
- platform: Test key for packages that are part of the core platform.
- shared: Test key for things that are shared in the home/contacts process.
- media: Test key for packages that are part of the media/download system.
To sign an app with one of the existing key, use the following instruction ( LOCAL_CERTIFICATE) into the associated makefile Android.mk:
Troubleshooting
Can not find Mac SDK or Required minimum for the macosx platform
Download and uncompress the exact missing Mac SDK version into the following directory:
Error: could not find jdk tools.jar
Need to defined $ANDROID_JAVA_HOME used in
Make error — already defined
If you got the following error during the AOSP compilation:
Go to the already defined directory and rename simply the Android.mk file to Android_old.mk
GC overhead limit exceeded
To increase the the heap size use the following command lines:
Case-insensitive filesystem
You are building on a case-insensitive filesystem.
Fatal error file not found
If the following error is raised during the Android building process:
Please check the filename user or lower case. Remember that the Android building process is case-sensitive.
In this case create a symbolic name xt_dscp.h for the original file xt_DSCP.h with the following command lines:
No space left on device
If the case-sensitive partition become full (no free space available):
Open Terminal and increase the partition size:
Missing and no known rule to make it
If the flowing error is raised during a single package compilation thought mm or mmm command:
Compile the bidding library metrics-helper:
Источник
UNITY3D DEVS — SETTING UP YOUR MAC FOR ANDROID BUILDS
May 12, 2018 · 5 min read
If you have landed up on this post, you must be wondering how to set everything up for making Android builds on your Mac.
I am pretty sure there are a bunch of similar articles or posts about this topic. But I found the information scattered here and there. Or, maybe I am just not smart enough. Anyways, once I figured out all the steps and went through them myself, I thought of documenting them for my team mates.
I am sharing the same here and I hope this post helps you or anyone else who is also gearing up for Android release. BTW, the steps / principles are the same if you are using Windows.
Let’s do this:
Once you have installed Android Studio you will see the landing dialog as seen below. (Below is the landing dialog for Android Studio ver. 2.3.3)
Step 2: Install the APIs / Android SDKs
Using Configure drop-down option (along the bottom edge of the screen) launch the SDK Manager and install the APIs you are interested in.
(In this particular project, as you can see in the image below, I was interested in API 25 aka Nougat aka Android 7.1.1). The SDK Manager is pretty straight forward tool — you can install and uninstall APIs as and when required. If you are working with multiple APIs, then you simply choose the ones you need to install.
Step 3: Download JDK
(You dont need Demos and Sample for Unity development, just the JDK)
Step 4: Install JDK
Double click on JDK Update package (as seen below)
The JDK installation wizard will fire up. Simply go through the wizard and complete the JDK installation process.
Step 5: Setting up JAVA_HOME environment variable
(This is an important step which is something you should not skip. I recommend you to please read all the instructions below once, before you start going through the steps.)
If you are trying to run a Java application on your Mac and need to set your JAVA_HOME, you need to do the following steps:
What is JAVA_HOME?
JAVA_HOME is the path to the folder that contains a sub-folder named bin. This in turn contains java. Typically, for Mac OSX it is /Library/Java/Home
- Open up Terminal
- First confirm you have JDK installed by typing which java in command line.
- It should show something like: /usr/bin/java
- Ensure you have the required version of Java. You can do that by typing: java -version
- Set JAVA_HOME by typing this command in Terminal:
- Then type echo $JAVA_HOME in command line to confirm the path is correctly set
- Now you should be able to run your Java application.
PLEASE NOTE: This ONLY sets JAVA_HOME for that particular instance of bash.
So do I need to do this every time?
No! If you want the configuration to be persistent, then you will have to add the command to your
NOTE: (Usually) there is no
/.profile by default.
So when you start Terminal, it loads a shell — in our case, bash. Shells may or may not have configuration files.
/.profile is nothing but a config file to set up your shell environment. They are a set of instructions which are executed before loading your shell environment. They are read when the shell starts up, in a specific order. You can specify the exact order in the
Assuming you don’t already have a
/.profile file using any text editor.
For example, in Terminal, type:
Okay, now that you have opened up
/.profile file in your text editor, you need to add the following commands. If
/.profile file already exists then I recommend to add the following commands to the end of the
Remember to save before closing the text editor 😊
If you have done all these steps: The next time you fire up an instance of bash, the commands in the
/.profile will be read & executed in the exact order as you have specified.
/.bash_profile always overrides
/.profile.
So if you write a
/.profile file won’t be read / executed anymore.
Step 6: Verification of Step 5 i.e. your JAVA_HOME is set and persistent
Open a brand new Terminal window (using cmd+n) and type in command line:
You should see something like the following:
java version “1.8.0_131”
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)
If you see the above:
Congratulation! ✌
Now you’ve successfully set your JAVA_HOME environment variable to /Library/Java/Home/bin/java and it’s persistent.
- Android Studio installed ✅
- APIs installed ✅
- JDK installed ✅
- JAVA_HOME is set ✅ and it’s persistent ✅
- Verified ✅
Well …. go on and try to build!
Go back to Unity (make sure you have switched your platform to Android) and start your build.
The Build will most likely fail will the following error in the console:
CommandInvokationFailure: Unable to list target platforms. Please make sure the android sdk path is correct. See the Console for more details.
/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java -Xmx2048M -Dcom.android.sdkmanager.toolsdir=”/Users/surathchatterji/Downloads/Android/sdk/tools” -Dfile.encoding=UTF8 -jar “/Applications/Unity/PlaybackEngines/AndroidPlayer/Tools/sdktools.jar”
Step 8: The good news, my friend, this is the final step. You are almost there!
So how should you fix this error?
I will try to simplify the steps for you:
- Go to this page and download the latest Android SDK Tools (zip file)
- Unzip it and you will get a tools folder
- Go to your Android SDK home location AndroidSDK->sdk->tools (delete this folder)
- Drag and drop the unzipped tools folder inside sdk folder (Essentially you are replacing the existing tools folder with the new one)
NOTE: The sdk-tools-darwin-3859397.zip on this page (right at the bottom of the page) did not work for me. Some devs did say that it worked for them! Just wanted to mention that, just in case.
Now you may go back to Unity -> (Once again: Make sure you have switched to Android platform) and BUILD!
Congratulations, now you have got your Trucker’s Hitch!
Источник