Tutorial: Create your first Android application
In this tutorial, we will create a simple yet fully-functional Android application that counts how many times you tap a droid image. After that, we will run it on an Android virtual device.
This tutorial covers a simple scenario to help you get started with Android development in IntelliJ IDEA. For comprehensive how-to guides and reference documentation, visit the Android Studio user guide.
Create a new Android project
Create a project
Launch IntelliJ IDEA. On the Welcome screen, click New Project . If you already have a project open, from the main menu select File | New | Project .
In the New Project wizard, select Android on the left.
If you don’t have the Android SDK configured, IntelliJ IDEA will detect this and prompt you to download it:
Select the components you want to install. If you haven’t installed the Android SDK tools before, all the required components will be preselected.
Optionally, modify the location for the Android SDK, and click Next :
Review the installation settings and click Finish to start the download:
When all components have been downloaded and installed, click Finish :
Select Empty Activity as the project template:
On the last step, type HelloDroid as the project name and select Java as the language:
Configure project JDK
Now that we have created our first project, let’s make sure it uses the correct JDK.
From the main menu, choose File | Project Structure and go to Platform Settings | SDKs . Select the Android SDK and make sure that the correct Java version is selected in the Java SDK field.
We recommend that you use Java SE 11 or Java SE 8 for Android development in IntelliJ IDEA. If you don’t have the correct JDK installed, in the Project Structure dialog, click the Add New SDK button on the toolbar and select Download JDK :
In the Settings dialog ( Ctrl+Alt+S ), go to Build, Execution, Deployment | Build Tools | Gradle and select the correct Java version (8.x or 11.x).
Explore the project structure
For Android projects, there’s a dedicated view in the IntelliJ IDEA Project tool window: click Project in the top-left corner and select Android .
This view doesn’t reflect the actual hierarchy of files on your disk — it is organized by modules and file types to ease navigation between source files of your project. Note that it hides project files and directories that you don’t commonly use (to see them, choose the Project view):
The app folder consists of the following subfolders:
manifests : contains the AndroidManifest.xml file, which holds general information about the application processed by the Android operating system. Among other things, it declares the package name that serves as a unique identifier for your application and the minimum version of the Android SDK required for the device where the application will run. It also declares the entry points of the application, along with permissions the application requires. For details, see App Manifest Overview.
java : contains the Java source code files grouped by packages, including JUnit tests.
res : contains all non-code resources, such as XML layout files, UI strings, images, and so on.
The Gradle Scripts folder contains all the project’s build-related configuration files.
Edit the UI layout
At this stage, the user interface of our sample HelloDroid application is based on a very simple layout defined in the activity_main.xml file located in the res/layout folder.
Let us modify the auto-generated user interface and see how the application layout is rendered without running it on any physical or virtual device.
Open the UI designer
In the Android project view, go to the app/res/layout and double-click the activity_main.xml file to open it. Note that since IntelliJ IDEA downloads the components required to render layout files, opening it may take a few seconds.
If the UI designer fails to open, and you get the Design editor is unavailable until after a successful project sync error, press Ctrl+Shift+A , search for the Sync Project with Gradle Files action, and wait for the sync to finish.
By default, IntelliJ IDEA provides a graphical view of the layout file, but you can also switch to the source code view, or view the text and the graphical representation side by side — use the icons in the top-right corner of the UI Designer pane:
This pane shows a rectangular canvas that is synchronized with the layout definition and with the Component Tree , so any changes to the canvas are reflected there accordingly.
Normally, layout files have a layout manager as their root element (for example, LinearLayout , FrameLayout , ConstraintLayout , and so on). In our example, the root element in activity_main.xml is ConstraintLayout that is responsible for positioning the elements of the application interface. For the purpose of this tutorial, we are not going to modify it, but you can learn more about designing interfaces from Build a Responsive UI with ConstraintLayout.
To eliminate distraction and only see how your layout is represented, click the Select Design Surface icon in the top-left corner and choose Design :
Now let’s delete the existing text element. To do this, right-click the text label and choose Delete from the context menu.
Now the UI layout looks like the following, and we are ready to start designing the layout of our application:
Add image to the UI layout
Now let’s add a droid image to our layout.
In the Android project view, expand the app/res folder and drag the image you want to use into the drawable folder. For this tutorial, we’ve downloaded a Hello Droid image from the Internet and saved it with the dimensions 50×50 px.
Return to the activity_main.xml file opened in the Designer pane, from the Palette choose the ImageView element, and drag it to the canvas to the position where you want the image to appear.
In the Pick a Resource dialog that opens, choose the resource file you’ve added and click OK :
Next, we need to modify the default id of the imageView element to be able to reference it later.
Select it in the Component Tree and in the Attributes pane on the right, enter the new identifier in the id field: droidImage . Press Enter ; in the dialog that opens, confirm that you want to update all references to the image element id:
Add text to the UI layout
Now let’s add some text to our layout.
In the Palette pane, pick the TextView element and drag it to the canvas below the image.
The widget displays some default text: TextView . To change it and link it to a string, we need to create a new text resource.
Select the textView element in the Component Tree on the left. In the Attributes pane on the right, click the Pick a Resource icon next to the text attribute:
In the dialog that opens, click the Add resource to the module icon in the top left corner and choose String Value .
In the New String Value dialog, enter the resource name ( welcome_text ) and the resource value ( Hello! I’m a droid. ):
Click OK to save the value and then click OK in the Pick a Resource dialog.
Now let’s modify the textView element id the same way we did with imageView .
Select textView in the Component Tree on the left, and in the Attributes pane set the id to a new value: clickCounter .
Add style to text
Now let’s add some style to the text to make it look more appealing.
Pad the text a bit: locate the padding attribute, and set all values to 10dp :
Change the font color: locate the textColor attribute, and click the Pick a Resource icon next to it.
In the dialog that opens, click the Add resource to the module icon in the top left corner and choose Color Value .
Enter the resource name ( text_color ) and the value ( #9C27B0 ):
Change the font size: locate the TextSize property and click the Pick a Resource icon next to it.
In the dialog that opens, click the Add resource to the module icon in the top left corner and choose Dimension Value .
Enter the resource name ( text_size ) and the value ( 24sp ):
As a result, your user interface now looks like the following:
To check what your application UI looks like in landscape orientation, click the Orientation for Preview icon on the Designer toolbar and choose Landscape :
To preview what your layout looks like on different devices, select another device from the device list:
Make the application interactive
Although our sample application is fully functional at this point, it does not support any form of interaction yet. Let’s modify it to support tap events.
In the Android project view, locate the MainActivity file under app\java\com.example.hellodroid and double-click to open it.
MainActivity is not a very meaningful class name, so let’s rename it.
Right-click this file in the Android project view and choose Refactor | Rename from the context menu or press Shift+F6 . In the dialog that opens, change the class name HelloDroidActivity and click Refactor :
All references to this class will be updated automatically, and your application’s source code will look as follows:
Replace the code in HelloDroid.java with the following:
Note that the identifiers we’ve used in the source code correspond to those we’ve set in our layout definition file, otherwise our code would not work.
Build and run the application
Now let’s build our application and run it on a virtual device.
Configure Android virtual device
First of all, to be able to run our application, we need to configure a virtual device.
In the main IntelliJ IDEA toolbar, click the devices list and choose AVD Manager :
On the first step of the wizard, click Create Virtual Device :
On the next step, we need to select the hardware that our virtual device will emulate.
Let’s select Phone on the left, and choose Pixel 2 as the target device:
Choose the system image you want to mimic on the virtual device, that is the OS version, the Android API level, the application binary interface (ABI), and the target SDK version:
Click the Download link next to the system image you want to mimic on the virtual device. For this tutorial, we’ve chosen to download the R system image.
In the License Agreement dialog that opens, read the license agreement and accept it, then click Next and wait for the download to finish. When the system image has been downloaded, select it and click Next in the System Image step of the wizard.
On the last step, you can modify your virtual device name and select the startup size and orientation of the screen. Choose the portrait layout and click Finish :
The newly configured device appears in the Android Virtual Device Manager .
Run the application
On the main IntelliJ IDEA toolbar, make sure the automatically created Run configuration and the virtual device we’ve just configured are selected and click :
The Android emulator will launch after the build has successfully finished, with our application started:
Click the droid image and see how the application processes the tap events, counts them and returns the corresponding message:
For information on how to run the app on a hardware device, refer to Android Studio: Run apps on a hardware device.
How do I set up IntelliJ IDEA for Android applications?
How do I set up IntelliJ IDEA for Android applications?
7 Answers 7
I’ve spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.
So here’s the full guide:
- Download and install Java JDK (Choose the Java platform)
- Download and install Android SDK (Installer is recommended)
- After android SD finishes installing, open SDK Manager under Android SDK Tools (sometimes needs to be opened under admin’s privileges)
- Choose everything and mark Accept All and install.
- Download and install IntelliJ IDEA (The community edition is free)
- Wait for all downloads and installations and stuff to finish.
New Project:
- Run IntelliJ
- Create a new project (there’s a tutorial here)
- Enter the name, choose Android type.
- There’s a step missing in the tutorial, when you are asked to choose the JDK (before choosing the SDK) you need to choose the Java JDK you’ve installed earlier. Should be under C:\Program Files\Java\jdk
- Choose a New platform ( if there’s not one selected ) , the SDK platform is the android platform at C:\Program Files\Android\android-sdk-windows .
- Choose the android version.
- Now you can write your program.
Compiling:
- Near the Run button you need to select the drop-down-list, choose Edit Configurations
- In the Prefer Android Virtual device select the . button
- Click on create, give it a name, press OK.
- Double click the new device to choose it.
- Press OK.
- You’re ready to run the program.
The 5th step in «New Project’ has apparently changed slightly since.
Where it says android sdk then has the drop down menu that says none, there is no longer a ‘new’ button.
- a.)click the . to the right of none.
- b.)click the + in the top left of new window dialog. (Add new Sdk)
- c.)click android sdk from drop down menu
- d.)select home directory for your android sdk
- e.)select java sdk version you want to use
- f.)select android build target.
- g.)hit ok!
Once I have followed all these steps, I start to receive error messages in all android classes calls like:
I revolved that including android.jar in the SDKs Platform Settings:
I had some issues that this didn’t address in getting this environment set up on OSX. It had to do with the solution that I was maintaining having additional dependencies on some of the Google APIs. It wasn’t enough to just download and install the items listed in the first response.
You have to download these.
- Run Terminal
- Navigate to the android/sdk directory
- Type «android» You will get a gui. Check the «Tools» directory and the latest Android API (at this time, it’s 4.3 (API 18)).
- Click «Install xx packages» and go watch an episode of Breaking Bad or something. It’ll take a while.
- Go back to IntelliJ and open the «Project Structure. » dialog (Cmd+;).
- In the left panel of the dialog, under «Project Settings,» select Project. In the right panel, under «Project SDK,» click «New. » > Android SDK and navigate to your android/sdk directory. Choose this and you will be presented with a dialog with which you can add the «Google APIs» build target. This is what I needed. You may need to do this more than once if you have multiple version targets.
- Now, under the left pane «Modules,» with your project selected in the center pane, select the appropriate module under the «Dependencies» tab in the right pane.
Just in case someone is lost. For both new application or existing ones go to File->Project Structure. Then in Project settings on the left pane select Project for the Java SDK and select Modules for Android SDK.
Another way to identify the correct SDK is to install Android Studio, create a new project, go to project structure, SDK Location and find where the SDK was installed.
I found using the default installation process on a mac that the SDK home folder was in the /Users/’yourUser’/Library/Android/sdk folder. Make sure you have enabled your Mac to view the Library folder.
В чем писать код начинающему Android-разработчику: выбираем IDE
Редакция блога Нетологии рассказала, что такое IDE, какие преимущества у IntelliJ IDEA и Android Studio и как установить программы.
Обучение в онлайн-университете: курс «Android-разработчик с нуля»
Чтобы перевести написанный вами код в понятный компьютеру, нужно использовать компилятор. Чтобы упростить задачу, используйте IDE, где для запуска приложения достаточно нажать кнопку Play.
Что такое IDE
IDE — среда разработки, текстовый редактор, заточенный на написание на одном или нескольких языках программирования. Программа выполняет несколько задач — упрощает работу с кодом и подготавливает рабочее окружение.
Как IDE помогает писать код
Программа понимает структуру языка программирования и выполняет следующие задачи.
- Подсказывает возможные ошибки, например, если вы забыли закрыть скобку. Программа сразу напомнит об этом и не придется тратить время на запуск, проверку сообщений об ошибках и правку. Это можно сравнить с подчеркиванием ошибок в Word.
- Когда вы используете какую-либо функцию, показывает документацию для нее. Это работает, как справка в Excel, когда вы применяете какую-либо функцию.
- Помогает быстро переименовать переменную. Если переменная использована в нескольких местах, все можно править в один клик.
- По мере написания кода ищет в нем ошибки и указывает на них.
В реальной жизни разработчик пишет меньше половины кода — остальное генерирует или подсказывает IDE.
Как IDE запускает приложение
Благодаря IDE не надо устанавливать и настраивать компилятор на нужные параметры, подключаться отладчиком к определенному процессу. Эти задачи выполнит среда разработки. Сразу после установки в ней можно написать первое приложение Hello World и запустить его по одному клику.
Какие IDE используют Java-разработчики
IntelliJ IDEA. Одна из популярных сред разработки. Доступна в двух версиях — бесплатной Community edition для самостоятельных разработчиков и платной Ultimate edition для компаний. Подходит для мобильной разработки под Android и десктопной Java для запуска на компьютере.
Android Studio. Основана на IntelliJ IDEA, предлагает все нужные функции и заточена под проекты на Android. IDE рекомендует Google, ее используют начинающие разработчики и опытные Android-девелоперы как Джейк Уортон.
IDE Eclipse не стоит использовать. Среда разработки устарела, и в 2016 году в Google отказались от поддержки ее плагинов для Android-разработки.
Преимущества IntelliJ IDEA
Мультиязычная. Поддерживает разные языки программирования. Вы сможете писать код на Java, дальше освоить Kotlin и использовать его.
Интегрирована с Git и Github. Позволяет использовать систему контроля версий Git и отправлять проекты на Github в один клик.
Позволяет настроить нужное окружение. Чтобы запускать тесты в IDE, достаточно докачать Java Devkit.
Как установить и настроить IntelliJ IDEA
Предварительно скачайте Java Development Kit по ссылке. Выберите версию для любой операционной системы. Рекомендуем установить JDK 8 если вы будете писать в Android Studio Android-приложения. Остальные могут использовать версию JDK 11.
Следуйте подсказкам установщика.
Скачайте Community Edition-версию программы по ссылке. Можно выбрать версию для любой операционной системы — Windows, MacOS или Linux.
Установите, следуйте подсказкам инсталлятора. При первом запуске программа предложит импортировать настройки. Так как установленных ранее версий не было, выберите Don’t import settings.
Программа предложит выбрать цветовую схему и дополнительные возможности. Выберите настройки по умолчанию и пропустите эти шаги.
Запустите программу. Когда откроется окно проекта, выберите Create New Project.
В верхнем левом углу выберите Java, нажмите Next.
В качестве шаблона выберите Java Hello World.
Выберите папку, в которую нужно сохранить проект.
В правом верхнем углу найдите зеленую кнопку Play и нажмите ее — вы запустили первую скомпилированную программу.
Преимущества Android Studio
Рекомендована Google. IDE поддерживают и развивают в корпорации, среда разработки оптимальна для создания приложений для Android.
Большое сообщество разработчиков. Почти все Android-девелоперы используют Android Studio. Если у вас возникнут проблемы в работе, сможете обратиться к коллегам на форумах или тематических сайтах — вам помогут.
Как установить Android Studio
Скачайте Java SDK, если их еще нет, и установите — программа нужна для дальнейшей работы на Java. После установки желательно перезагрузить компьютер.
Скачайте Android Studio, откройте exe-файл и запустите его. Кликните Download, чтобы операционная система вашего ПК определилась автоматически, или выберите нужную вручную в Download Options. Нажимайте Next, пока установщик не спросит путь. Первый укажите для Android Studio, второй — для Android SDK. Желательно ставить на диск D, так как программа занимает от 2 Гб.
Нажимайте Next, пока не завершится установка. Откройте установленную Android Studio. Откажитесь от импорта настроек предыдущей версии — старых настроек у вас нет.
Google предложит отправлять уведомления о работе приложения. На них можно согласиться или отказаться.
Выберите Standart в следующем окне.
Установщик сообщит, что нужно докачать несколько компонентов — нажмите Next и дождитесь окончания загрузки распаковки.
Нажмите Finish — откроется Welcome экран. Нажмите Start a new Android Studio project.
Мнение автора и редакции может не совпадать. Хотите написать колонку для «Нетологии»? Читайте наши условия публикации. Чтобы быть в курсе всех новостей и читать новые статьи, присоединяйтесь к Телеграм-каналу Нетологии.
Android JNI + Intelij Idea + Gradle. Полная автоматизация процесса
Доброго времени суток!
Данный пост является небольшим руководством, по автоматизации компиляции нативного кода в среде Intellij Idea с использованием Gradle. Gradle предоставляет достаточно большой функционал для автоамтизации сборки проектов. Но даже подключение нативных библиотек к Android проекту требует дополнительных усилий со стороны разработчика.
Предыстория
Недавно я сменил место работы и устроился работать в компанию, занимающуюся разработкой собственного мобильного программного обеспечения. Мы с моими новыми коллегами по работе решили перейти с Eclipse (на котором до этого велась вся разработка) на Intellij Idea, и в добавок с Ant на Gradle. У нас достаточно большой проект, с приличным количеством кода, в том числе с использованием нативного C и C++ кода, как самописного так и уже готовых библиотек.
Тех, кто занимается разработкой Android проектов с использованием Android NDK в среде Intellij Idea + Gradle прошу под кат.
На скорую руку
Что касается java кода мы достаточно легко перенесли весь процесс разработки на новую IDE и систему сборки, не буду углубляться в данный процесс. С переносом нативного кода было все гораздо сложнее.
Так как нам не дали достаточно времени на поиск подходящего решения сразу, поэтому мы просто собрали все модули нативного проекта для необходимых нам платформ, положили в папку с исходниками нашего проекта и воспользовались быстро найденным решением для автоматического включения их в наш apk файл, данный подход описан в этой статье.
Поиск подходящего решения
На самом деле первый подход какое-то время нас абсолютно устраивал. Библиотеки были давно протестированы, и нам не приходилось часто вносить изменения в нативный код, до недавнего времени, когда нам понадобилось дописать еще один модуль. Тогда мы стали искать решение как компилировать весь наш исходный код, включая нативный.
Выяснилось что Gradle игнорирует Android.mk файлы и создает свои. Для этого он предоставляет большой функционал по передаче различных флагов и свойств ndk. Об это хорошо написано в этой статье. Но нам больше нравилось использовать возможности по компиляции, с использованием *.mk файлов.
По этому мы вспомнили что Gradle предоставляет большой функционал для собрки и попробовали, напрямую вызвать ndk-build скрипт, который предоставляет Android NDK.
Для того чтобы это происходило автоматически, была написана отдельная Gradle-задача и добавлена к зависимостям задачи по автоматической упаковке нативных библитек. Вот вырезка из build.gralde файла нашего модуля:
В принципе данного кода уже достаточно чтобы компилировать нативные исходники в автоматическом режиме и подключать их к проекту. Но мы работаем в команде и не хорошо если каждый будет исзменять под себя основной файл сборки, потому что ‘path/to/ndk/’ у всех будет скорее всего свой. Поэтому, было решено вынести путь до NDK в файл локальных настроек сборки проекта.
Файл local.properties должен находится в корне проекта. Если вы добавляете данный файл, то необходимо будет указать не только директорию NDK, но и директорию SDK, иначе Gradle выдаст соответствующее предупреждение, и откажется собирать ваш проект.
Теперь меняем нашу Gradle-задачу, добавляя использование локального пути до NDK.