- How to make Android apps without IDE from command line
- How to do Android development faster without Gradle
- IntelliJ IDE, but not Gradle
- 1. Install Java
- 2. Install all SDK tools
- 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…
- 3. Code the application
- How to use JavaMail on Android (without Gradle)
- Hello guys!
- 4. Build the code
- 5. Sign the package
- 6. Align the package
- 7. Test the application
- 8. Make a script
- Notes
- Пишем и собираем приложения для Android в linux консоли
- Введение
- Железо
- Операционная система
- Установка пакетов
- Настройка adb
- Постановка задачи
- Создание подписи
- Манифест
- Layout
- Исходный код приложения
- Скрипт для сборки
- Сборка и установка
- Заключение
- How To Install Android SDK Tools On Ubuntu 20.04
- Download SDK Tools
- Install SDK Tools
- Download and Install Platform Tools
- Configure Environment Variable
- Using the SDK Manager
- Using the Emulator and AVD Manager
- Summary
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:
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…
Источник
Пишем и собираем приложения для 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 Install Android SDK Tools On Ubuntu 20.04
It provides all the steps required to install Android SDK Tools on Ubuntu 20.04 LTS.
In this tutorial, we will discuss all the steps required to install Android SDK Tools, SDK Manager, and AVD Manager on the popular Linux distribution i.e. Ubuntu 20.04 with Java 16. This tutorial provides the steps to install Android SDK Tools on Ubuntu 20.04 LTS, though the steps should be the same for other versions of Ubuntu and Linux systems.
This post is useful for the developers using Android SDK Tools with other IDEs without installing Android Studio for the use cases including hybrid app development using Ionic. It also assumes that a valid JAVA_HOME environment variable exists pointing to the installation directory of Java. You may follow the Java installation tutorials written by us including How To Install Java 8 On Ubuntu, How To Install Java 16 On Ubuntu 20.04 LTS, and How To Install OpenJDK 16 On Ubuntu 20.04 LTS.
In case you are interested in developing Android applications using Android Studio, you can also follow the other tutorials written by us including How To Install Android SDK Tools On Windows, How To Install Android Studio On Windows, and How To Install Android Studio On Ubuntu 20.04.
You may also be required to execute the below-mentioned command in case you have set the options previously for Java 9 or Java 10.
Notes: The Ubuntu 18.04 LTS version of this tutorial is available at — How To Install Android SDK Tools On Ubuntu 18.04. You can continue this tutorial for Ubuntu 20.04 LTS.
Download SDK Tools
Open the download tab of Android Studio and scroll down to the Command line tools only section. This section shows various options to download the SDK tools as shown in Fig 1.
Click on the Download Link as highlighted in Fig 1. It will ask to accept the Terms and Conditions as shown in Fig 2.
Go through the details, agree to the terms and conditions, and click the Download Button to start the download.
Install SDK Tools
In this step, we will install the Android SDK Tools on Ubuntu. Create a directory having the name set to android-sdk and extract the content of the downloaded SDK Tools zip to this directory. Create another directory android-sdk/cmdline-tools to store the sdk-tools. Make sure that the tools directory is available directly within the android-sdk/cmdline-tools directory created by us.
Download and Install Platform Tools
In this step, we will install the Android Platform Tools on Ubuntu. Follow the same steps similar to Android SDK Tools as shown in Fig 4, Fig 5, and Fig 6 to install Android Platform Tools using the download link.
Make sure that the platform-tools content is available within the directory platform-tools. The directory structure should be similar to:
Configure Environment Variable
In this step, we will configure the environment variable to use the SDK tools installed by us. There are two ways to do it. In the first approach, we can update the .bashrc file of the user account. Another approach is to update /etc/profile file which works for all the accounts.
Approach A
Update .bashrc file of the user account.
Notes: Replace the android sdk path based on your installation directory.
Approach B
Update /etc/profile file.
Scroll down by pressing the Page Down button and add at the end of this file:
Make sure that you provide the correct path to the android-sdk directory.
Now press Ctrl + O and press Enter to write our change. Press Ctrl + X to exit the nano editor. The nano editor should look like Fig 7.
Notes: Approach B didn’t work for me.
Now test the Android SDK installed by us using the environment variables configured by us.
Using the SDK Manager
Update SDK Manager — Update the SDK manager using the below-mentioned command.
List — We can list the installed and available packages and images using the list command as shown below.
Install Platform — Use the below-mentioned command to install the Android 10 (API level 29) using the SDK manager.
It will ask to accept the terms and conditions. Enter y and hit Enter Key to accept the terms and conditions. This command creates the directories licenses and platforms within android-sdk and installs the package android-30 within the platforms directory having all the required files to run the emulator for Android 11.
If we again check the installed packages, the list command shows the installed options as shown below.
After installing the platforms, the directory structure should be:
Add System Image — We can add system image from available images shown by the list command using the SDK manager as shown below. We are adding the most recent default 64-bit system image.
Accept the License Agreement to complete the download. There are several projects which need Google Play Services. We need system images specific to Google Play Services as shown below.
Now again use the command list as shown below.
After installing the default system image, the directory structure should be:
Install Emulator — You might be required to install the emulator before creating the AVD using SDK Manager. The emulator gets installed while adding the system images in the previous steps.
Install Build Tools — Install the most recent build tool listed by the list command.
After installing the build tools, the directory structure should be:
Now again use the command list as shown below.
Using the Emulator and AVD Manager
Create AVD — Create the AVD using the system image downloaded in the previous step as shown below. Replace with actual name.
The above commands ask a bunch of questions to configure the AVD if we choose the custom hardware profile option. We have excluded the details of these options from this tutorial since these configuration details depend on the actual needs. After completing all the configurations, it creates the AVD using the name provided by us while configuring it.
List AVDs — Now go to the tools directory(only required in case you have omitted to add tools path to PATH while configuring environment variables) on the command line and check the installed platform as shown below.
It will list all the AVDs installed by us.
Launch AVD — We can launch the AVD using the emulator as shown below.
The emulator will take some time to completely launch the AVD. The final results should look similar to Fig 8.
Notes: I have used Ubuntu 20.04 LTS installed as VM using VMware Workstation Player, hence I have enabled the Virtualization for my Virtual Machine.
Delete Emulator — We can also delete an existing emulator as shown below.
Summary
This tutorial provided all the steps required to install Android SDK Tools and Android Platform Tools on Ubuntu 20.04 LTS. It also provided the steps required to launch the AVD using the Android Emulator.
Источник