We write and collect Android applications in the linux console

image


In this article I will show how you can build an apk file in Ubuntu using only
command line utilities.


Usually, Android Studio is used to create applications for Adroid. But to build small programs, you can do the command line. For example, when computer resources are limited and your application is very simple.


As a permanent development environment, this may not be very convenient, but if you
sometimes need to build some small utilities - this is just right.


Introduction


Android development is not the main focus of my activity, I sometimes make some small applications for my needs.


I used to use QPython, but it is quite heavy and inconvenient to work with. Therefore, I proceeded to the development of native programs. Even with a superficial knowledge of Java,
this is not a big deal.


This guide is heavily based on this document: Building an Android App
from the Command Line
. For anyone interested in the details, refer to the source.


Similar article: We wrote, assembled and launched HelloWorld for Android in notepad already found on this resource, but it examined development in Windows.


Here I will discuss how you can build an application in linux.


Iron


Testing was carried out on an old netbook with an Atom processor, 1GB of RAM
and an 8GB SSD drive.


operating system


I tested the application on Ubuntu 17.04. Starting with Ubunu 16.04, android-sdk can be installed through the package manager.


Manual SDK Download

In principle, the same SDK can be
downloaded from the site .
Downloading a file from the section 'Get just the command line tools'
In fact, this does not change the process much, but through the package manager everything is much simpler.
The difference will only be in the ways and installation of additional packages "android-platform".


Package Installation


So, let's proceed to the installation.


sudo apt install android-sdk

A large number of packages will be installed, including Java.


Further, depending on the required version of Android, you need to install the correct
version of packages. For lolipop 5.1 you must set:


sudo apt install google-android-platform-22-installer
sudo apt install google-android-build-tools-22-installer

It is also necessary to install an additional package.


sudo apt install apksigner

If you plan to install the apk package via adb , then a little additional settings are needed.


Adb setup


Use lsusb to find a connected device


# lsusb
....
Bus 001 Device 004: ID 1782:75b0 MyDevice
....

And create a file with the rule:


sudo vi /etc/udev/rules.d/51-android.rules

Add one line to the file:


SUBSYSTEM=="usb", ATTR{idVendor}=="1782", MODE="0666", GROUP="plugdev"

Here "1782" is taken from the output of lsusb .


Restart service


sudo systemctl restart udev

After connecting via adb , you need to confirm the connection on the device.


Now everything is ready to go.


Formulation of the problem


The application we are going to build is a bit more complicated than the 'Hello world'.


  • It is required to take a line from the clipboard at the click of a button.
  • Cut substring
  • Write the substring back to the buffer.
  • Use Toast to output a substring or error message.

In general, everything is simple.


I prepared an example which we will take as a basis.


Signature Creation


First, create a key to sign the file:


keytool -genkeypair -keystore keystore.jks -alias androidkey \
      -validity 10000 -keyalg RSA -keysize 2048 \
      -storepass android -keypass android

This will come in handy later.


Manifesto


AndroidManifest.xml

Here we indicate the name of the application in the attribute "android: label" . The application will also use its icon, it is indicated in the attribute "android: icon" . The icon itself lies in the directory "res / drawable-mdpi" file "icon.png". As an icon, you can take any small png file.


Layout


The file with the arrangement of elements is located in the directory "/ res / layout /".


activity_main.xml

You can add widgets to it if you want to expand the functionality.


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


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


MainActivity.java
package ru.kx13.extractvidid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.content.ClipboardManager;
import android.content.ClipData;
public class MainActivity extends Activity {
  private static String extract(String s) {
    int start = s.indexOf("%3D");
    int end = s.indexOf("%26");
    if(start == -1 ||  end == -1) {
      return "error";
    }
    return s.substring(start + 3, end);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView text = (TextView)findViewById(R.id.my_text);
    text.setText("Извлечь  youtube video id");
    Button button = (Button) findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        ClipboardManager myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData abc = myClipboard.getPrimaryClip();
        ClipData.Item item = abc.getItemAt(0);
        String text = item.getText().toString();
        String video_id = MainActivity.extract(text);
        ClipData myClip = ClipData.newPlainText("text", video_id);
        myClipboard.setPrimaryClip(myClip);
        Toast toast = Toast.makeText(getApplicationContext(), 
            video_id, Toast.LENGTH_SHORT); 
        toast.show(); 
      }
    });
  }
}

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


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


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


build.sh
#!/bin/sh
SOURCE=ru/kx13/extractvidid
BASE=/usr/lib
SDK="${BASE}/android-sdk"
BUILD_TOOLS="${SDK}/build-tools/22.0.1"
PLATFORM="${SDK}/platforms/android-22"
mkdir -p build/gen build/obj build/apk
"${BUILD_TOOLS}/aapt" package -f -m -J build/gen/ -S res -M AndroidManifest.xml -I "${PLATFORM}/android.jar"
javac -source 1.7 -target 1.7 -bootclasspath "${JAVA_HOME}/jre/lib/rt.jar" \
         -classpath "${PLATFORM}/android.jar" -d build/obj \
         build/gen/${SOURCE}/R.java java/${SOURCE}/MainActivity.java
"${BUILD_TOOLS}/dx" --dex --output=build/apk/classes.dex build/obj/
"${BUILD_TOOLS}/aapt" package -f -M AndroidManifest.xml -S res/  -I "${PLATFORM}/android.jar" \
        -F build/Extractor.unsigned.apk build/apk/
"${BUILD_TOOLS}/zipalign" -f 4 build/Extractor.unsigned.apk build/Extractor.aligned.apk
apksigner sign --ks keystore.jks \
        --ks-key-alias androidkey --ks-pass pass:android \
              --key-pass pass:android --out build/Extractor.apk \
              build/Extractor.aligned.apk

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


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

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


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


./build.sh

If everything is configured correctly, no messages will be displayed, and the file "Extractor.apk" appears in the "build" directory


Now we need to install our application


adb install -r build/Extractor.apk

If everything went fine, a new application will appear on the device. You can run and use.


In general, you can transfer the apk file to the device in any convenient way.


Conclusion


As you can see from the article, it’s not difficult to start development in the console.


Console utilities allow you to develop programs with very small resources.


Have a nice development!


Also popular now: