Android development with linux

Содержание
  1. Пишем и собираем приложения для Android в linux консоли
  2. Введение
  3. Железо
  4. Операционная система
  5. Установка пакетов
  6. Настройка adb
  7. Постановка задачи
  8. Создание подписи
  9. Манифест
  10. Layout
  11. Исходный код приложения
  12. Скрипт для сборки
  13. Сборка и установка
  14. Заключение
  15. How To Set Up Android Development Tools On Linux
  16. Android Development Tools On Linux
  17. Install Java
  18. Ubuntu
  19. Debian
  20. Arch Linux
  21. Fedora
  22. OpenSUSE
  23. Generic Linux
  24. Download Android Studio
  25. Install Android Studio
  26. Android Command-line Tools
  27. Ubuntu
  28. Debian
  29. Arch Linux
  30. Fedora
  31. OpenSUSE
  32. Generic Linux
  33. Leave a Reply Cancel reply
  34. Android
  35. Contents
  36. Transferring files
  37. App development
  38. Android Studio
  39. SDK packages
  40. Android Emulator
  41. Other SDK packages in the AUR
  42. Making /opt/android-sdk group-writeable
  43. Other IDEs
  44. Netbeans
  45. Vim / Neovim
  46. Emacs
  47. Other Tools
  48. Marvin
  49. Building
  50. Required packages
  51. Java Development Kit
  52. Setting up the build environment
  53. Downloading the source code
  54. Building the code
  55. Testing the build
  56. Creating a flashable Image
  57. Flashing
  58. Fastboot
  59. Samsung devices
  60. samloader
  61. Heimdall
  62. Odin (Virtualbox)
  63. Use Android on GNU/Linux
  64. Troubleshooting
  65. Android Studio: Android Virtual Devices show ‘failed to load’.
  66. Android Studio: ‘failed to create the SD card’
  67. Eclipse: During Debugging «Source not found»
  68. ValueError: unsupported pickle protocol
  69. libGL error: failed to load driver: swrast OR AVD does not load and no error message displayed
  70. sh: glxinfo: command not found
  71. Android Emulator: no keyboard input in xfwm4
  72. Android Emulator: Window is shaking and blinking when used in WM tiled mode
  73. Android Emulator: Segmentation fault (core dumped)
  74. adb: sideload connection failed: insufficient permissions for device

Пишем и собираем приложения для Android в linux консоли

В данной статье я покажу как можно собрать apk файл в Ubuntu используя лишь
утилиты командной строки.

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

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

Введение

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

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

Данное руководство в большой степени базируется на этом документе: Building an Android App
from the Command Line. Кому интересны подробности, обращайтесь к первоисточнику.

Похожая статья: Пишем, собираем и запускаем HelloWorld для Android в блокноте уже встречалась на этом ресурсе, но в ней было рассмотрена разработка в Windows.

Здесь же я рассмотрю, как можно собрать приложение в linux.

Железо

Тестирование проводилось на стареньком нетбуке с процессором Атом, 1Гб ОЗУ
и 8Гб SSD диска.

Операционная система

Я тестировал приложение на Ubuntu 17.04. Начиная с Ubunu 16.04 android-sdk можно установить через пакетный менеджер.

В принципе, тот же SDK можно
скачать с сайта.
Качать файл из раздела ‘Get just the command line tools’
По сути это не сильно меняет процесс, но через пакетный менеджер все гораздо проще.
Разница будет лишь в путях и установке дополнительных пакетов «android-platform».

Установка пакетов

Итак, приступим к установке.

Будет установлено большое количество пакетов, включая Java.

Далее, в зависимости от требуемой версии Android, необходимо установить нужную
версию пакетов. Для lolipop 5.1 необходимо ставить:

Так же необходимо установить дополнительный пакет.

Если вы планируете устанавливать apk-пакет через adb, то необходимо немного дополнительных настроек.

Настройка adb

С помощью lsusb найти подключенное устройство

И создать файл с правилом:

В файл добавить одну строку:

Здесь «1782» взято из вывода lsusb.

После подключения через adb, на устройстве необходимо подтвердить соединение.

Теперь все готово к работе.

Постановка задачи

Приложение, которое будем собирать немного сложнее, чем ‘Hello world’.

  • Требуется по нажатию кнопки взять строку из буфера обмена.
  • Вырезать подстроку
  • Записать подстроку обратно в буфер.
  • С помощь Toast вывести подстроку или сообщение об ошибке.

В общем-то все просто.

Я подготовил пример который возьмем за основу.

Создание подписи

Сначала создадим ключ для подписи файла:

Это нам пригодится позже.

Манифест

Здесь указываем имя приложения в атрибуте «android:label». Так же приложение будет использоваться свою иконку, она указана в атрибуте «android:icon». Сама иконка лежит в каталоге «res/drawable-mdpi» файл «icon.png». В качестве иконки можно взять любой небольшой png файл.

Layout

Файл с расположением элементов находится в каталоге «/res/layout/».

В него можно добавлять виджеты, если вы захотите расширить функционал.

Исходный код приложения

Исходный код приложения находится здесь «java/ru/kx13/extractvidid»

Код весьма прост и примитивен, но этот шаблон можно использовать в других приложениях.

Скрипт для сборки

Я не стал использовать утилит сборки типа make или ant, т.к. весь код находится в одном файле и особых преимуществ это не даст. Поэтому это обычный shell скрипт:

Некоторые замечания по поводу путей.

  • По умолчанию, переменная BASE указывает на путь, в который пакетный менеджер сохраняет файлы. Если вы ставите SDK вручную, то путь надо будет изменить.
  • Если вы используете версию API отличную от 22, то вам надо подправить переменные BUILD_TOOLS и PLATFORM

Сборка и установка

Для сборки просто запустите

Если все настроено правильно никаких сообщений не будет выведено, а в каталоге «build» появится файл «Extractor.apk»

Теперь надо установить наше приложение

Если все прошло нормально, на устройстве появится новое приложение. Можно запускать и пользоваться.

В общем случае можно перекинуть файл apk на устройство любым удобным способом.

Заключение

Как видно из статьи начать разработку в консоли совсем несложно.

Консольные утилиты позволяют разрабатывать программы при весьма небольших ресурсах.

Источник

How To Set Up Android Development Tools On Linux

Aug 8, 2018
Comment

Increasingly, Android app development on Linux is growing. The main reason behind this is that the Linux platform makes it super easy to get a full developer workstation going (compared to other platforms.) Development is one of Linux’s strong suits, so naturally, setting up Android development tools on Linux is easy.

SPOILER ALERT: Scroll down and watch the video tutorial at the end of this article.

Читайте также:  Spdif windows 10 работает звука нет

Android Development Tools On Linux

Android Studio is Google’s complete development suite for creating software on the Android platform. It comes with dozens of tools, emulation setup, and code to work with.

Note: Before attempting to install this software, please install Java. Failing to install Java will make Android Studio unusable.

Install Java

Getting Java for Linux differs, depending on the operating system you’re using. Generally, most Linux distributions have excellent support for OpenJDK. It’s an open implementation of the Java tools. It’s best to go this route, and most developers won’t notice the difference. Follow the instructions below to get Java working on your distribution.

Note: aside from OpenJDK, you may need to install other dependencies to run Android Studio on your Linux PC. For more information, check out the official guide page for Linux.

Ubuntu

Ubuntu users have easy access to OpenJDK. As of Ubuntu version 18.04, OpenJDK 11 is available. To install it, open up a terminal and use the Apt package management tool to get it going.

Need more than just the standard OpenJDK 11 package? Check out these other packages.

Debian

Debian is a Linux distribution that focuses primarily on solid, stable software. It is because of this, the absolute latest version of OpenJDK is hard to get ahold of (version 11). Still, it is possible to get version 8, which is functional.

Note: if you absolutely have to have version 11, consider upgrading Debian from “Stable” to “Testing,” or at the very least using backports.

Alternatively, install all Java JDK 10 stuff into Debian with:

Arch Linux

Arch Linux is bleeding edge Linux, so there’s no issue getting a fairly current version of OpenJDK working correctly. Unfortunately, despite how recent Arch is, there’s currently no builds of version 11. Still, users have access to OpenJDK 10, which is fairly new.

To install the software, open up a terminal and use the Pacman packaging tool to get it running.

Fedora

Fedora Linux has version 10 of OpenJDK, which should be enough to run and develop on Android Studio. To install it, use the DNF package management tool in the terminal.

OpenSUSE

Depending on what version of OpenSUSE you use, your packages are either very new or very old. For this reason, getting one version of OpenJDK working across all versions of SUSE is a bit tricky.

To get OpenJDK working, head over to the download page for OpenSUSE. On the download page, select the version of OpenJDK you’d like, then click the “install” button to start the installation process.

Generic Linux

Many Linux distributions (even the obscure ones) use OpenJDK because it’s safe to include in software repositories. As a result, installing OpenJDK is incredibly easy. To get it working open up a terminal and search your package manager for “OpenJDK”. Alternatively, download it from the official website.

Download Android Studio

Unfortunately, Android Studio doesn’t have a downloadable binary package. Instead, users looking to use the development suite on Linux will need to download a compressed archive file.

Head over to the official download page and click on the Linux download link. Read through the EULA and check the box to accept the agreement to start the download. When the download finishes, open up a terminal window and use the Unzip tool extract Android Studio.

Using the CD command, move the terminal into the bin subfolder.

Install Android Studio

Start the Android Studio installation tool with:

In the Android Studio Wizard, select the “Standard” option. When the Android Studio Wizard finishes the installation process, click the “Start a new Android Studio” option to begin development.

Android Command-line Tools

Aside from Android Studio, there are other important development tools for Linux that you may want to install. Specifically, command-line tools that allow users to interact with devices on Linux. Thankfully, installing these command-line tools isn’t as tedious as Android Studio.

To get the Android command-line tools working on Linux, follow the instructions below that match your Linux OS.

Ubuntu

Debian

Arch Linux

Fedora

OpenSUSE

Generic Linux

Need the Android command-line tools but can’t find them in your Linux distribution’s software repository? Google has a standalone download for those that need it. Head over to the official download page, and scroll down to “command line” to get it.

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Android

Contents

Transferring files

There are various ways to transfer files between a computer and an Android device:

  • USB cable
    • Media Transfer Protocol for modern Android devices
    • USB mass storage for older devices
    • Android Debug Bridge
  • special USB sticks / regular USB stick with adapter
  • Bluetooth
  • Arch Linux software with Android counterparts
    • client or server for protocols that can be used to transfer files (eg. SSH, FTP, Samba or HTTP)
    • KDE Connect ( kdeconnect ) – integrates your Android device with the KDE or Gnome desktop (featuring synced notifications & clipboard, multimedia control, and file/URL sharing).
    • cloud synchronization clients
    • Syncthing
    • sendanywhereAUR – cross-platform file sharing
    • qrcpAUR – transfer files over wifi from your computer to your mobile device by scanning a QR code

App development

The officially supported way to build Android apps is to use #Android Studio.[1]

Android Studio

Android Studio is the official Android development environment based on IntelliJ IDEA. It provides integrated Android developer tools for development and debugging.

The Android Studio Setup Wizard installs the required #SDK packages and places the SDK by default in

To build apps from the command-line (using e.g. ./gradlew assembleDebug ) set the ANDROID_SDK_ROOT environment variable to your SDK location.

Читайте также:  Отдельный жесткий диск для windows

SDK packages

Android SDK packages can be installed directly from upstream using #Android Studio’s SDK Manager or the sdkmanager command line tool (part of the Android SDK Tools). Some Android SDK packages are also available as AUR packages, they generally install to /opt/android-sdk/ .

Android SDK Package SDK-style path AUR package AUR dummy CLI tools
Command-Line Tools tools android-sdk-cmdline-tools-latest AUR android-sdk-cmdline-tools-latest-dummy AUR apkanalyzer, avdmanager, lint, retrace, screenshot2, sdkmanager
SDK Build-Tools build-tools;version android-sdk-build-tools AUR android-sdk-build-tools-dummy AUR aapt, aapt2, aidl, apksigner, bcc_compat, d8, dexdump, dx, lld, llvm-rs-cc, mainDexClases, split-select, zipalign
SDK Platform-Tools platform-tools android-sdk-platform-tools AUR android-sdk-platform-tools-dummy AUR adb, dmtracedump, e2fsdroid, etc1tool, #fastboot, hprof-conv, make_f2fs, make_f2fs_casefold, mke2fs, sload_f2fs, sqlite3, systrace
SDK Platform platforms;android-level android-platform AUR , older versions android-platform-dummy AUR (unnecessary)

The android-tools package provides adb, #fastboot, e2fsdroid and mke2fs.android from the SDK Platform-Tools along with mkbootimg and ext2simg .

Android Emulator

The Android Emulator is available as the emulator SDK package, the android-emulator AUR package, and there is also a dummy package for it: android-emulator-dummy AUR .

To run the Android Emulator you need an Intel or ARM System Image. You can install them through the AUR[2], with the sdkmanager or using Android Studio’s AVD Manager.

Other SDK packages in the AUR

The Android Support Library is now available online from Google’s Maven repository. You can also install it offline through the extras;android;m2repository SDK package (also available as android-support-repository AUR ).

Making /opt/android-sdk group-writeable

The factual accuracy of this article or section is disputed.

The AUR packages install the SDK in /opt/android-sdk/ . This directory has root permissions, so keep in mind to run sdk manager as root. If you intend to use it as a regular user, create the android-sdk users group, add your user.

Set an access control list to let members of the newly created group write into the android-sdk folder. As running sdkmanager can also create new files, set the ACL as default ACL. the X in the default group entry means «allow execution if executable by the owner (or anyone else)»

Re-login or as log your terminal in to the newly created group:

Other IDEs

Android Studio is the official Android development environment based on IntelliJ IDEA. Alternatively, you can use Netbeans with the NBAndroid-V2. All are described below.

Netbeans

If you prefer using Netbeans as your IDE and want to develop Android applications, use NBAndroid-V2 .

Install android-sdk AUR package and follow the instructions from the NBANDROID README.

Vim / Neovim

It is possible to write flutter applications for Android and iOS using (Neo)vim like an IDE. Install coc using a Vim plugin manager. Also install the coc-flutter extension for autocompletion (like in Android Studio) and to load the code into an Android emulator.

Emacs

To develop a mobile flutter application using Emacs, as the the official instruction at flutter.dev suggests, install lsp-dart.

Other Tools

Marvin

Marvin is a tool which helps beginners set up an Android development environment. Installing marvin_dsc AUR helps you set up the following things: JDK, Android SDK, IDE(s), and AVD.

Building

Please note that these instructions are based on the official AOSP build instructions. Other Android-derived systems such as LineageOS will often require extra steps.

Required packages

As of 2020/April, to build either AOSP 10 or LineageOS 17.1 you need (possibly a subset of) base-devel , multilib-devel , gcc , repo , git , gnupg , gperf , sdl , wxgtk2 , squashfs-tools , curl , ncurses , zlib , schedtool , perl-switch , zip , unzip , libxslt , bc , rsync , ccache , lib32-zlib , lib32-ncurses , lib32-readline , ncurses5-compat-libs AUR , lib32-ncurses5-compat-libs AUR , and a TTF font installed (e.g. ttf-dejavu ). In particular, no Python2 or Java are required, as they are provided by AOSP/Lineage. The aosp-devel AUR metapackage provides them all for simple installation.

Additionally, LineageOS requires the following packages: xml2 AUR , lzop , pngcrush , imagemagick . They can be installed with the lineageos-devel AUR metapackage.

The factual accuracy of this article or section is disputed.

Java Development Kit

The required JDK version depends on the Android version you are building:

  • For Android 9 (Pie) and up, Java is included with the Android source and no separate installation is needed.
  • For Android 7 and 8 (Nougat and Oreo), OpenJDK 8 is required, which is available with the jdk8-openjdk package.
  • For Android 5 and 6 (Lollipop and Marshmallow), OpenJDK 7 is required, which is available with the jdk7-openjdk package.

Set JAVA_HOME to avoid this requirement and match the Arch Linux installation path. Example:

This change will be valid only for the current terminal session.

Setting up the build environment

Create a directory to build.

The Android build process expects python to be python2. Prepend it to the PATH :

Alternatively, create a python2 virtual environment and activate it:

/android to reflect your build directory if different than above).

or (assuming build directory Data/Android_Build):

Downloading the source code

This will clone the repositories. You only need to do this the first time you build Android, or if you want to switch branches.

  • The repo has a -j switch that operates similarly to the one used with make . Since it controls the number of simultaneous downloads, you should adjust the value depending on downstream network bandwidth.
  • You will need to specify a branch (list of branches) to check out with the -b switch. If you leave the switch out, you will get the so-called master branch.

The -c switch will only sync the branch which is specified in the manifest, which in turn is determined by the branch specified with the -b switch, or the default branch set by the repository maintainer.

Wait a long time. Just the uncompiled source code, along with the .repo and .git directories that are used to keep track of it, are very large. As of Android 10, at least 250 GB of free disk space is required.

Building the code

This should do what you need for AOSP:

Читайте также:  X skh cursors курсор мыши для windows 10

If you run lunch without arguments, it will ask what build you want to create. Use -j with a number between one and two times number of cores/threads.

The build takes a very long time.

Testing the build

When finished, run/test the final image(s).

Creating a flashable Image

To create an image that can be flashed it is necessary to:

This will create a zip image under out/target/product/hammerhead (hammerhead being the device name) that can be flashed.

Flashing

In some cases, you want to return to the stock Android after flashing custom ROMs to your Android mobile device. For flashing instructions of your device, please use XDA forums.

Fastboot

Fastboot (as well as ADB) is included in the android-tools package.

Samsung devices

Samsung devices cannot be flashed using Fastboot tool. Alternatives are Heimdall and Odin (by using Windows and VirtualBox).

samloader

To download original Samsung firmware, a platform independent script, samloader can be used.

Heimdall

Heimdall is a cross-platform open-source tool suite used to flash firmware (also known as ROMs) onto Samsung mobile devices and is also known as an alternative to Odin. It can be installed as heimdall .

The flashing instructions can be found on Heimdall’s GitHub repository or on XDA forums.

Odin (Virtualbox)

It is also possible to restore firmware (Android) on the Samsung devices using Odin, but inside the VirtualBox.

Arch Linux (host) preparation:

  1. Install VirtualBox together with its extension pack and guest additions.
  2. Install your preferred, but compatible with Odin, Windows operating system (with VirtualBox guest additions) into a virtual hard drive using VirtualBox.
  3. Open VirtualBox settings of your Windows operating system, navigate to USB, then tick (or make sure it is ticked) Enable USB 2.0 (EHCI) Controller.
  4. At VirtualBox running Windows operating system, click in the menu bar Devices > USB Devices, then click on your Samsung mobile device from the list, which is connected to your computer via USB.

Windows (guest) preparation:

Check if configuration is working:

  1. Turn your device into Download mode and connect to your Linux machine.
  2. In virtual machine toolbar, select Devices > USB > . Samsung. device.
  3. Open Odin. The white box (a big one at the bottom-left side) named Message, should print a line similar to this:

which means that your device is visible to Odin & Windows operating system and is ready to be flashed.

Use Android on GNU/Linux

There are several projects and methods which support running Android on GNU/Linux:

  • Anbox: container-based software to run Android on Linux kernels
  • Android-x86: a direct port of Android for the x86 architecture

Troubleshooting

Android Studio: Android Virtual Devices show ‘failed to load’.

Make sure you have exported the variable ANDROID_HOME as explained in #Android Studio.

Android Studio: ‘failed to create the SD card’

If you try to run an AVD (Android Virtual Device) under x86_64 Arch and get the error above, install the lib32-gcc-libs package from the multilib repository.

Eclipse: During Debugging «Source not found»

Most probably the debugger wants to step into the Java code. As the source code of Android does not come with the Android SDK, this leads to an error. The best solution is to use step filters to not jump into the Java source code. Step filters are not activated by default. To activate them: Window > Preferences > Java > Debug > Step Filtering. Consider to select them all. If appropriate you can add the android.* package. See the forum post for more information: http://www.eclipsezone.com/eclipse/forums/t83338.rhtml

ValueError: unsupported pickle protocol

One fix is to issue:

If that does not work, then try this:

libGL error: failed to load driver: swrast OR AVD does not load and no error message displayed

Sometimes, beginning to load an AVD will cause an error message similar to this to be displayed, or the loading process will appear to finish but no AVD will load and no error message will be displayed.

The AVD loads an incorrect version of libstdc++, you can remove the folder libstdc++ from

/.android-sdk/emulator/lib64 (for 64-bit) or

/.android-sdk/emulator/lib (for 32-bit) , e.g.:

Note that in versions before Android Studio 3.0, this directory was in a different location:

Alternatively you can set and export ANDROID_EMULATOR_USE_SYSTEM_LIBS in

Fix for the .desktop file might be achieved by using env command, prefixing the Exec line Desktop entries#Modify environment variables

sh: glxinfo: command not found

Here is the full error:

You can try to install glxinfo ( mesa-demos ) but if your computer has enough power you could simply use software to render graphics. To do so, go to Tools > Android > AVD Manager, edit the AVD (click the pencil icon), then select Software — GLES 2.0 for Emulated Performance > Graphics.

Android Emulator: no keyboard input in xfwm4

In xfwm4, the vertical toolbar buttons window that is on the right of the emulator takes focus from the emulator and consumes keyboard events. (bug report)

You can use the workaround described in [3]:

  1. Open the xfwm4 settings.
  2. Switch to the Focus tab.
  3. Change the Focus Model to «Focus follow mouse».
  4. Disable Automatically raise windows when they receive focus option below.\

Android Emulator: Window is shaking and blinking when used in WM tiled mode

When using Tiled Window Manager like dwm, Android Emulator will shake and blink. You can use the workaround described in krohnkite issue 72 (window floating is induced by Alt+f in dwm).

Android Emulator: Segmentation fault (core dumped)

When using Nouveau drivers try to disable gpu hardware acceleration.

In some devices it can only be done by editing $HOME/.avd/device_name.avd/config.ini .[4]

  1. Set hw.gpu.enabled=no
  2. Set hw.gpu.mode=off

adb: sideload connection failed: insufficient permissions for device

If you get the error:

you might solve it by restarting the adb server:

Источник

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