Android development with linux

Пишем и собираем приложения для 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.

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.

Источник

Best Linux Distro For Android Development: A Comparison!!

This article is for those of you who are Linux-users/Distro-hoppers/Android-developers who are trying to find the perfect distro to do their android development activities in. Android is built on top of the Linux kernel, which makes Linux the ideal Operating System to develop android in. This goes for both application development, custom ROM development and even kernel development. Let’ go ahead and explore what choice we have and analyze their differences in an attempt to choose the best Linux Distro for Android Development activities.

Let’s start by look at the short version of the answer for those of you in a hurry to start your Android development activities!

The Short Answer

Winner: BBQ Linux

Runner up: Ubuntu and it’s variants

3rd Place: FWUL

That is just the short version of the answer, let’s go ahead and look at the longer and more informative version and learn what were the factors considered, what other choices you have and see why BBQ Linux is chosen as the best distro for android development along with some valuable resources for getting started with your android development activities!

The Analysis

Linux has already captured a huge percentage of the server market and it is the most dominant player there. As Linux is getting more and more famous lots of distros are being developed to enhance the desktop support for Linux.

Читайте также:  Как переделать андроид под ios

The setup programmers would need for coding will be radically different than the setup artists and video editors would need for content creation and editing! Hence some factors that are considered important for using Linux as a workstation depend upon the kind of work that you are planning to do with it.

But some factors are common across all types of work. These include

If you plan to do all of your productive activities on your next Linux distro then I suggest reading the article I wrote recently given in the link below where I have analyzed and compared several options in order to figure out what is the best distro for workstation purposes.

In this article, we will be focussing on the needs of Android developers and let’s see what those needs are in the next section.

The Needs of an Android Developer

The basic tools needed for Android development include the following.

Basic Tools

  • Java, using which all android apps are built
  • Android Studio IDE
  • The official Android SDK which comes with the Software Development Kits for various versions of Android OS along with tools like
    • Android Virtual Device(AVD) for emulating an Android device on your PC through QEMU, which again has kernel support in Linux to make it run faster than other operating systems
    • Android Device Monitor to analyze the resource usage on your Android device to get information similar to what you will get using the System Monitor app on Linux or the Task Manager app on windows.
    • Android Device Bridge(ADB) a command-line tool which can be used for communicating and executing commands on your Android device

The above tools are all you need to start developing Android apps. But then they aren’t the only tools out there, as a professional android developer you are going to need so much more! Let’s have a look at some of the other tools that will help with your android development activities.

Advanced Android Tools

  • AOSP development tools like OmniROM, cyanogen mod, etc to help you build your own custom ROM for your Android device straight from the Source code of Android. These tools can come in handy if you work for a smartphone manufacturer or if you wish to make your own custom ROM for your personal smartphone.
  • Game development tools like Unity and Unreal engines. Even though you can still make simple games using the Android Development Studio, you are going to need these pro tools to build your cool game idea into a great mobile game!
  • SimpleADB: a GUI interface for ADB and fastboot tools.
  • FireBase: Googles platform for web and mobile developers
  • ML kit: Googles machine learning kit for AI apps

Manufacturer Specific Tools

This list can go on and on with tools specific for given smartphone manufacturers like

  • SP Tools for MediaTek devices
  • Heimdall for flashing firmware onto Samsung devices,
  • SALT for managing LG devices,
  • Sony Flashtool for flashing firmware onto sony devices,
  • MIFlash for Xiaomi devices,
  • ROME to extract ROMs, etc.

Other tools

Other essential development tools which are common to all programmers are

  • a good text editor like VS Code or Atom,
  • DevOps tools like GitLab or GitHub

These are just a small list of endless tools you may need to install and configure before you can start your development activities. Hence it is a good decision to waste less time and go ahead with a distro that comes in with all the tools you will ever need so that you don’t have to waste time and do everything manually wasting a good hour or 2 each time you need one of the above-mentioned tools!

Distro Choices That Match These Needs

Let’s take a look at the 3 most popular distros among android developers and see which one shines in what aspects in this section!

Ubuntu and its Derivatives

I am sure you did not come to this article expecting to see Ubuntu on the list! But there is a reason for it being here, among all the top distros, Ubuntu is the one giving some thought to moving into the smartphone arena with its Ubuntu phone. Because of that the android tools that are made available through the official Ubuntu repos are made to go through a rigorous testing process to make sure it will perform just the way we expect them to!

Also Ubuntu is a very popular distro you and is known for its stability, you can count on it to not break on you every once in a while, leading to endless hours of trying to fix your computer!

I am not a fan of Ubuntu’s Unity desktop environment, if you are someone like me, I suggest giving one of their flavors or derivatives a try like Kubuntu, Linux Mint, etc. You can read more about these flavors in my other article given below.

With that being said let’s look at some of the pros and cons of choosing ubuntu for your android development needs.

Pros of choosing Ubuntu

  • Stability
  • good online community support
  • android tools are tested by the distro provider

Cons of choosing Ubuntu

  • you still need to manually install all the software mentioned in the section above, which is not a good use of your time!

BBQ Linux

BBQ Linux is a distro focussed solely on Android development. It is made by an XDA developer and is based on Arch Linux. Here is an introduction snippet of BBQ from its humble website

BBQLinux is based on Arch Linux and is using a rolling release development model which means it is getting continually updated and upgraded. It will never be necessary to re-install a later release of BBQLinux. It is fully compatible with Arch Linux and is using the Arch package repos plus a BBQLinux specific one. The default desktop environment is “CINNAMON” but we’re also providing images with “MATE”, “GNOME”, “PLASMA” and “XFCE4”.

You can test BBQLinux without doing any modifications to your computer using our live media.

Читайте также:  Как соединить смарт часы с андроидом

This distro comes with all the goodies you will need to start your android development so that you don’t have to waste too much time installing the required software packages on your Linux machine. You can find a complete list of packages that come as part of your download in this link

A screenshot of that link is shown below

As you can see BBQ Linux already has most of the tools you need like android SDK, android studio, etc,. setup and ready to go! It even ships with some manufacturer-specific tools like Heimdall!

Pros of choosing BBQ Linux

  • This distro comes with many software packages that you will need for your android development efforts
  • Based on Arch Linux which is known for a rolling release model and is a very popular distro with a very good community following.

Cons of choosing BBQ Linux

  • Arch Linux has the nature of expecting users to solve any problems they might have using their online documentation, which means there will be some learning curve associated with it.

FWUL

Another distro made by an XDA developer, FWUL is meant to be targetted on android hobbyists rather than pro developers and as such FWUL comes bundled with all the cool tools and toys you will ever need if you wish to start hacking your phone in your free time!

FWUL stands for Forget Windows Use Linux, a fun name indeed and according to the creator the story behind the name was

FWUL … Why? .. and why this name?
The existence of FWUL has a simple reason. I wanted to have something where I were able to point users to when they came with issues on Windows because the most problems around were solvable when using Linux …

… and so the generic answer I gave those were exactly what FWUL means today. The only issue with Linux (even with Ubuntu, Mint and such) is that they do not include everything an Android user needs. You still have to issue commands to install and you have to make other adjustments like udev rules etc. Nothing a “normal” Windows user can do without guidelining.

That was the main reason why I started FWUL.. and because I had the above in mind FWUL is named like this.
easy right?

Similar to BBQ Linux, this one is also an Arch Linux derivative, more specifically it is a derivative of Manjaro which in turn is a derivative of Arch Linux.

This one comes with all the tools an Android hobbyist will ever need to mod his/her phone. The screenshot below shows some of the included tools like SimpleADB, Heimdall, SALT, ROME, MiFlash etc. You can visit this link to see a full list of tools that come with this distro.

link

Some tools like SPI Flash tools, Sony Flash tools, etc. are not packaged with the distro in order to keep the distro lightweight and due to some licensing issues. To make it easier to install these tools the distro comes with simple installers prebuilt so that you can just double click and install these other tools! Thoughtful indeed by the developer behind the distro!

Pros of choosing FWUL

  • Best collection of tools for an android hobbyist
  • Based on the popular Manjaro distro

Cons of choosing FWUL

  • FWUL doesn’t cater to the needs of a professional Android developer.

Best Distro For Android Development

Now that we have seen 3 distros popular among the android developer community, let’s go ahead and choose one! As you have already read at the beginning of the article, my choice was BBQ Linux. Let’s look at the reasons why I think BBQ Linux is our best bet.

  • The goal of this distro matches with the focus of this article and it is the only one to do so!
  • Comes with android studio preinstalled
  • Comes with AOSP tools for making custom ROMs
  • Based on Arch Linux a very old and popular distro

In short BBQ Linux comes with all the toys and goodies that you will ever need for your android development needs! Ubuntu is a close second place, and FWUL though a Linux distro focussed on Android, the target users are hobbyists and not professional developers and hence FWUL gets the third place!

Of course, you can make a good android development workstation with any distro of your choice, so if you are into that sorta thing then go ahead and do that, I am sure it will be a fun project!

And with that, I will conclude this article!

I hope you guys enjoyed this article and learned something useful.

If you liked the post, feel free to share this post with your friends and colleagues!

bbqlinux.org: The official BBQ Linux homepage

fwul.binbash.rocks: The official FWUL homepage

Here are some of my other articles that might interest you!

Источник

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