Building android apps on linux

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:

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:

Читайте также:  Как восстановить жесткий диск после linux

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…

Источник

Top Android Emulators to Run and Test Android Apps on Linux

Last updated July 21, 2021 By Ankush Das 7 Comments

Android is built on top of a heavily customized Linux kernel. So, running mobile apps on Linux makes sense using an Android emulator.

While this is not something new that you can do on your Linux machine, it is a feature more in demand after Windows introduced the ability to run Android apps in 2021.

Not just limited to using apps, some of the Android emulators can also come in handy for development and testing.

Hence, I have compiled a list of the best emulators that you can use to test or run Android applications/games on Linux.

1. Anbox

Anbox is a pretty popular emulator that lets Linux users run Android apps. Probably this is what Deepin Linux utilizes to make help run Android apps out of the box.

It isolates the Android operating system from the host using a container, which also lets them make the latest Android version available to use.

Android apps running will not have direct access to your hardware—which is a good security decision.

Читайте также:  Logitech f310 mac os драйвер

Unlike some of the other options here, Anbox does not technically need an emulation layer to make Android work. In other words, it is as close to a native Android experience on your Linux system.

For this reason, it may not be the easiest option available. You cannot just use the Google Play Store to install applications, you need to utilize Android Debug Bridge (ADB). All you need is the APK file of an app to install and use it.

2. Genymotion

Genymotion is an impressive solution tailored for testing and development.

It is not a free and open-source option. They provide virtual Android experiences as a service through the cloud or a desktop client that is independent of Android Studio.

You can simulate a variety of hardware configurations and Android versions to create a virtual device for testing. It also gives you the ability to scale up and has multiple Android virtual devices running for extensive tests.

It can help you test how file uploading works in your app, impacts battery, performance, memory, and so on.

While it is a premium solution mostly for professionals, it does support the latest Linux distributions that include Ubuntu 20.04 LTS.

3. Android-x86

Android x86 is an open-source project to make Android run on a PC with 32-bit support.

You can choose to install it using a virtual machine manager on your Linux system or directly try it on your PC.

Official installation instructions are available if you need to go ahead.

Unlike some other options, it is a simple emulator that tries to work on a PC with no fancy features.

4. Android Studio (Virtual Devices)

Android Studio is a full-fledged tool for development and testing. Fortunately, with the support for Linux, you can use it to emulate the Android experience for experiments if you need to.

You just need to create an Android Virtual Device (AVD) that you can configure and then simulate as an emulator.

There are good chances to find support for some of the latest smartphones, TVs, and smartwatches as well.

It needs a certain learning curve to be able to pull it off, but it is free and completely open-source.

5. ARChon

An interesting solution is an Android emulator that you can use in Linux and any other platform.

It helps run Android apps on Chrome OS or with Chrome browser on any operating system. Unlike some others, you may not get a complete Android experience but only the ability to run Android apps.

You just have to unpack the runtime and load it into Chrome extensions. Next, add the app you want to use by downloading the APK file onto it.

6. Bliss OS

Bliss OS is yet another open-source project, similar to Android x86 that aims to make Android run on PC.

Unlike Android x86, it gives more compatibility options by supporting both 32-bit and 64-bit architectures. Also, you can download the compatible file as per your processor.

It is actively maintained and supports the latest Android versions available in the market.

Wrapping Up

While you will find several Android emulators available for Linux, they may not replace a full-fledged smartphone experience.

Every emulator comes with a set of features along with a specific purpose. Choose the one that you need!

Have you tried Android emulators yet? What’s your favorite emulator that you have used in Linux? Feel free to let me know in the comments down below.

Like what you read? Please share it with others.

Источник

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

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

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

Читайте также:  Windows сменить значок тип файла

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

Введение

Разработка под 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 на устройство любым удобным способом.

Заключение

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

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

Источник

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