Run android studio from terminal

Использование терминала при разработке под Андроид

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

Моя цель в этой статье — поделиться с вами тем, как я использую терминал при разработке под Android.

iTerm2

Поскольку мы собираемся проводить много времени в командной строке, давайте установим терминал получше, нежели стандартный. Предлагаю вашему вниманию iTerm2.

ITerm2 — современный терминал с функциями, которые вы так давно желали видеть. Например, разбиение панели, пользовательские цветовые схемы, история, контроль над горячими клавишами, а также множество других удобных настроек, которые вы найдете полезными.

oh-my-zsh

Когда вы запускаете терминал, он запускает оболочку под названием Bash. Bash на сегодняшний день является самой популярной оболочкой и поставляется с почти каждой операционной системой на базе UNIX. Однако есть альтернативы Bash, которые делают использование терминала более быстрым и удобным для разработчиков.

По умолчанию oh-my-zsh поставляется с плагином, который предоставляет множество полезных функций.

Автозаполнение

Zsh-autosuggestions — это быстрые/ненавязчивые предложения для вставки в zsh. Он предлагает команды по мере ввода на основе истории команд:

Обратный умный поиск

Вы можете нажать Control + R, чтобы выполнить обратный умный поиск в истории команд. Начните вводить команду, и оболочка будет автозаполнена с ранее введенными командами.

Затем вы можете либо нажать Enter, чтобы выполнить предложенную команду, либо используйте стрелки влево/вправо, чтобы отредактировать команду, или продолжайте нажимать Control + R для переключения между другими возможными командами.

DryRun

Вы наткнулись на классную библиотеку github, но что вам нужно сделать, чтобы протестить ее на вашем телефоне?

  • Нажать кнопку Скачать zip
  • Извлечь zip-файл
  • Открыть Android Studio
  • Импортировать скачанный проект
  • Sync gradle
  • Запустить проект
  • Выбрать устройство
  • Опробовать
  • Удалить папку проекта и zip-файл, когда вам это более не требуется.

Вы можете использовать dryrun:

Билдим проект быстрее/без сети

Флаг —offline говорит gradle всегда использовать модули зависимостей из кеша, независимо от того, должны ли они быть проверены. При работе в автономном режиме, gradle никогда не попытается получить доступ к сети для выполнения разрешения зависимостей. Если требуемые модули отсутствуют в кэше зависимостей, выполнение сборки завершится с ошибкой.

Сборка на полной скорости:

Выполнение ваших модульных тестов на полной скорости:

В качестве альтернативы, в Android Studio вы можете сделать gradle build полностью офлайн, активировав эту опцию:

Settings -> Build, Execution, Deployment -> Build tools -> Gradle

Как Android-разработчик, вы, вероятно, используете Android Studio с Gradle. Одним из замечательных преимуществ является управление зависимостями, которое автоматически загружает артефакты из репозитория и делает их доступными для вашего приложения. В принципе, вы просто добавляете одну строку в файл build.gradle, и ваша библиотека включена. Довольно легко, правда?

Читайте также:  Система видеонаблюдения для андроид

Но вы точно знаете эту строку?

Для этого существует ALFI:

  1. Введите: alfi NAME_OF_THE_LIBRARY
  2. Скопируйте нужную библиотеку
  3. Вставьте в build.gradle

Не требуется взаимодействие с пользовательским интерфейсом и до 20 результатов сразу!

Понимание gradle задач

Если вы запустите ./gradlew tasks, вы получите список доступных функций gradle. То, что не указано в списке, это короткие версии команд, так что вот небольшой список допущений, которые вы можете сделать,

  • iDD == installDevelopmentDebug
  • aDD == assembleDevelopmentDebug
  • cC == connectedCheck
  • etc.

Вы можете начать делать следующим образом:

Так гораздо компактнее.

Android Rocket Launcher

Это gradle плагин, который добавляет задачи к вашим модулям Android для установки и запуска всех вариантов, поэтому нет необходимости запускать ./gradlew installDebug и переходить на телефон, находить приложение среди 50 приложений, которые вы установили, и запускать нужное.

Все, что вам нужно сделать, это добавить 2 строки в build.gradle

Совет: не забывайте, что даже при запуске приложения с терминала вы всегда можете активировать процесс отладки без необходимости перезапускать приложение.

Вывод юнит-тестов на консоль

Небольшой трюк, который позволяет увидеть результаты тестирования устройств Android.

Теперь, когда вы запускаете свои тесты, они выводят что-то вроде этого:

Удобные logcats

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

Этот небольшой инструмент решает эту проблему путем фильтрации по пакету приложения. Поставьте нужный пакет в качестве единственного аргумента и получите желаемый результат.

Источник

Как запустить Android Studio с помощью терминала

Я только что установил Android Studio. После установки я забыл добавить в лаунчер. Я перезапустил систему.

Теперь я хочу запустить Android Studio из терминала. Я попробовал все, но не сработало.

5 ответов

cd в каталог, куда вы распаковали zip-файл установщика android studio. Папка называется android-studio. Это может быть в вашем

/Downloads папку, если вы скачали ее из интернета. В настоящее время cd в папку bin и запустите файл studio.sh

На убунту это /opt/android-studio/bin/studio.sh

Вы можете открыть терминал, нажав CTRL + ALT + T

Просто запустите эту команду в свой терминал

cd / usr / local / android-studio / bin

/ usr / local / android-studio / bin $./studio.sh

Перейдите в папку android studio в вашей системе, затем 1. Нажмите правую кнопку мыши и откройте терминал 2. wright ./studio.sh и нажмите ввод 3. это откроет ваш эмулятор Android в Ubuntu

Если вы хотите использовать терминал для запуска программы, вы должны знать команду, которая будет написана в терминале. Чтобы узнать команду в Kubuntu, я использую Kmenuedit. В kmenuedit найдите эту программу и детали этой программы, там будет поле с именем command, там вы найдете текст, который будет написан в терминале. Другой вариант — проверить программу монитора системы, в которой также есть столбец с именем command. Таким образом, вы можете проверить запущенные экземпляры программ и команд.

Источник

How To Install And Run Android Studio On Linux

This article will tell you how to install and run the android studio on Linux. It is not similar to Windows and macOS. If you are a beginner to the android studio, this is very helpful to you.

1. Install Android Studio On Linux Steps.

  1. Download related android studio version from android studio official website. It is just a zip file.
  2. Unzip the download zip file to a local directory for example /home/zhaosong/WorkSpace/Tool/android-studio-ide-181.5056338-linux.
  3. Please note there is also another subfolder named android-studio in the above folder. Now the android studio has been installed successfully.

2. Start Android Studio On Linux.

Start android studio on Linux is also not similar to Windows or macOS, you should run the start script in the terminal to start it.

  1. Open a terminal and go to the android studio unzipped folder.
  2. CD into the bin folder in the android-studio folder.
  3. Execute $ ./studio.sh command in the terminal, then you can see the android studio startup as normal. Maybe there will have some error messages are printed in the terminal but it does not matter.
Читайте также:  Как снять экран со звуком андроид

3. Specify Android SDK And JDK Path In Android Studio.

When the android studio is started, click File —> New —> New Project to create a new android project. If you want to change the default Android SDK and JDK to other folders, you can follow the below steps.

  1. Click File —> Other Settings —> Default Project Structure… menu item in the android studio top menu bar.
  2. Then you can change the android studio project SDK and JDK folder in the popup dialog window SDK Location & JDK location section. If you are a beginner, you do not need to change them at all.

4. Add Android SDK Command Tool In System PATH.

Generally, you will use android studio to run the android SDK command tool, but sometimes you may need to invoke those android SDK commands in the terminal, so please follow the below steps to add android SDK command execute path in Linux PATH system environment variable value then you can invoke them in the command line.

Источник

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:

Читайте также:  Распайка шнура usb для зарядки андроид

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…

Источник

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