Как начать программировать под Android? Пошаговый план
В этой статье мы рассмотрим, как начать программировать под Android. Пошаговый план с ссылками на ресурсы, курсы и книги и типичные вопросы, которые задают на собеседованиях на позицию junior Android-разработчика. Ну а если вы хотите быстро за 12 занятий вникнуть в азы Android — то приглашаю на практический онлайн-интенсив где вы с наставником разработаете собственный проект.
Итак, вы решили начать программировать под операционную систему Android. Для начала, вам нужно изучить язык программирования. В мире Android на момент написания статьи (март 2020) года используются как Java, так и Kotlin, однако второй официально рекомендован компанией Google и набирает всё большую популярность, так что, если вы не знаете ни одного языка программирования — то можете изучать Kotlin, если же вы уже знаете какой-либо объектно-ориентированный язык программирования, то изучить Java или Kotlin для вас не составит труда. На рынке тренд идет в сторону Kotlin.
Изучаем язык
Kotlin
Чтобы освоить Kotlin, вам могут пригодиться, следующие ресурсы:
-
— набор примеров и заданий по Kotlin cразу с консолью, в которой можно ввести код и проверить — туториал от Google — набор мини-курсов для быстрого старта в Android — разработке — Книга Джоша Скина и Дэвида Гринхола основана на популярном курсе Kotlin Essentials от Big Nerd Ranch. Яркие и полезные примеры, четкие объяснения ключевых концепций и основополагающих API не только знакомят с языком Kotlin, но и учат эффективно использовать его возможности — хороший видеокурс, объясняющий основы программирования на Kotlin
Чтобы освоить Java, вам могут пригодиться, следующие ресурсы:
-
— эта книга не только научит вас теории языка Java и объектно-ориентированного программирования, она сделает вас программистом. В ее основу положен уникальный метод обучения на практике. В отличие от классических учебников информация дается не в текстовом, а в визуальном представлении. — курс от Udacity, который поможет вам изучить Java — эта книга является классикой для Java-программистов. Для новичков может быть несколько сложновата, но постарайтесь прочитать ее хотя бы половину и вернитесь к ней через годик, все сразу станет на свои места. Кстати, многие вопросы на собеседовании по Java взяты именно отсюда, так что не ленитесь, почитайте. — Эта книга давно уже признана авторитетным, исчерпывающим руководством и практическим справочным пособием для опытных программистов, стремящихся писать на Java надежный код для реальных приложений. Быстро освоить основной синтаксис Java, опираясь на имеющийся опыт и знания в программировании.
Изучаем Android SDK
Как только вы освоили базовый синтаксис и поняли базовые концепции, переходите к изучению Android SDK, параллельно читая перечисленные выше книги. Изучение Android SDK вы можете начать с таких ресурсов как:
-
— набор туториалов для начинающих Android-разработчиков от Google на языке программирования Kotlin. Из курса вы узнаете об основных компонентах Android SDK, таких как Activity, Intent, BroadcastReceiver и других. — курс на Udacity, где за 6 месяцев вам расскажут от том как разрабатывать мобильные приложения под Android — набор лекций об устройстве Android от Яндекс. Часть материала немного устарела, но даже сейчас будет очень полезна как начинающим, так и уже более-менее опытным разработчикам. — достаточно понятная книга для новичков, чтобы понять программирование под Android OS — книга, которая уже, наверное стала классикой для Android — программистов, один из самых полных источников знаний по Android OS
Это далеко не полный список, материалов огромное количество, но изучив вышеперечисленные ресурсы, вам с запасом хватит знаний для программирования под Android. Главное — не забывайте ежедневно практиковаться, общаться с наставником или ментором чтобы быстрее понимать свои ошибки и учиться на них.
Изучаем популярные библиотеки
Итак, вы неплохо знаете синтаксис языка, понимаете ООП, умеете применять наследование там где оно нужно и ваши приложения более-менее работают. Возможно, еще без применения архитектуры (MVP/MVVM/VIPER/RIBs) и без навороченных библиотек или фрэймворков. Самое время изучить и их.
В этом разделе я приведу список наиболее популярных библиотек, который используются в большинстве Android — проектов. Изучив их, вы смело сможете претендовать на звание junior или даже middle — разработчика.
Для многопоточного программирования
-
или бесплатный базовый курс по RxJava — набор туториалов и документация по корутинам от Jet Brains
- Основы работы с WorkManager— туториал по работе с WorkManager — туториал от Google как рабоать с корутинами и LiveData
Библиотеки для Dependency injection
- Dagger2
- Koin — пошаговый туториал для изучения основ
Библиотеки для сетевого взаимодействия
-
— пошаговый туториал, где вы создадите приложение для поиска фильмов
Библиотеки для обработки изображений
- Picasso
- Glide
Библиотеки для работы с Json
- GSON
- Jackson
- Moshi
Библиотеки для хранения данных
-
— мини-курс, который поможет понять основы Room + LiveData
- Realm
Изучив, материалы из этого списка вы уверенно сможете претендовать на роль джуниор-разработчика, а в следующем посте мы рассмотрим наиболее часто задаваемые вопросы на собеседованиях. А прямо сейчас приглашаю вас на онлайн-интенсив по разработке
Пишем первое приложение для Android
В любом деле самое сложное — это начало. Часто бывает тяжело войти в контекст, с чем столкнулся и я, решив разработать свое первое Android-приложение. Настоящая статья для тех, кто хочет начать, но не знает с чего.
Статья затронет весь цикл разработки приложения. Вместе мы напишем простенькую игру “Крестики-Нолики” с одним экраном (в ОС Android это называется Activity).
Отсутствие опыта разработки на языке Java не должно стать препятствием в освоении Android. Так, в примерах не будут использоваться специфичные для Java конструкции (или они будет минимизированы на столько, на сколько это возможно). Если Вы пишете, например, на PHP и знакомы с основополагающими принципами в разработке ПО, эта статья будет вам наиболее полезна. В свою очередь так как, я не являюсь экспертом по разработке на Java, можно предположить, что исходный код не претендует на лейбл “лучшие практики разработки на Java”.
Установка необходимых программ и утилит
-
; ;
- IDE c поддержкой разработки для Android:
- Eclipse + ADT plugin;
- IntelliJ IDEA Community Edition;
- Netbeans + nbandroid plugin;
Утилиты устанавливаются в определенном выше порядке. Ставить все перечисленные IDE смысла нет (разве только если Вы испытываете затруднения с выбором подходящей). Я использую IntelliJ IDEA Community Edition, одну из самых развитых на данный момент IDE для Java.
Запуск виртуального устройства
Запустив AVD Manager и установив дополнительные пакеты (SDK различных версий), можно приступить к созданию виртуального устройства с необходимыми параметрами. Разобраться в интерфейсе не должно составить труда.
Список устройств
Создание проекта
Мне всегда не терпится приступить к работе, минимизируя подготовительные мероприятия, к которым относится создание проекта в IDE, особенно, когда проект учебный и на продакшн не претендует.
Итак, File->New Project:
По нажатию кнопки F6 проект соберется, откомпилируется и запустится на виртуальном девайсе.
Структура проекта
На предыдущем скриншоте видна структура проекта. Так как в этой статье мы преследуем сугубо практические цели, заострим внимание лишь на тех папках, которые будем использовать в процессе работы. Это следующие каталоги: gen, res и src.
В папке gen находятся файлы, которые генерируются автоматически при сборке проекта. Вручную их менять нельзя.
Папка res предназначена для хранения ресурсов, таких как картинки, тексты (в том числе переводы), значения по-умолчанию, макеты (layouts).
src — это папка в которой будет происходить основная часть работы, ибо тут хранятся файлы с исходными текстами нашей программы.
Первые строки
Как только создается Activity (экран приложения), вызывается метод onCreate(). IDE заполнила его 2 строчками:
Метод setContentView (равносильно this.setContentView) устанавливает xml-макет для текущего экрана. Далее xml-макеты будем называть «layout», а экраны — «Activity». Layout в приложении будет следующий:
Для этого приложения идеально подойдет TableLayout. Id можно присвоить любому ресурсу. В данном случае, TableLayout присвоен При помощи метода findViewById() можно получить доступ к виду:
Теперь необходимо реализовать метод buildGameField(). Для этого требуется сгенерировать поле в виде матрицы. Этим будет заниматься класс Game. Сначала нужно создать класс Square для ячеек и класс Player, объекты которого будут заполнять эти ячейки.
Square.java
Player.java
Все классы нашего приложения находятся в папке src.
Game.java
Инициализация Game в конструкторе KrestikinolikiActivity.
Метод buildGameField() класса KrestikinolikiActivity. Он динамически добавляет строки и колонки в таблицу (игровое поле):
В строке 8 создается объект, реализующий интерфейс View.OnClickListener. Создадим вложенный класс Listener. Он будет виден только из KrestikinolikiActivity.
Осталось реализовать логику игры.
Определение победителя
К. О. подсказывает, что в крестики-нолики выирывает тот, кто выстроет X или O в линию длиной, равной длине поля по-вертикали, или по-горизонтали, или по-диагонали. Первая мысль, которая приходит в голову — это написать методы для каждого случая. Думаю, в этом случае хорошо подойдет паттерн Chain of Responsobility. Определим интерфейс
Так как Game наделен обязанностью выявлять победителя, он реализует этот интерфейс. Настало время создать виртуальных «лайнсменов», каждый из которых будет проверять свою сторону. Все они реализует интерфейс WinnerCheckerInterface.
WinnerCheckerHorizontal.java
WinnerCheckerVertical.java
WinnerCheckerDiagonalLeft.java
WinnerCheckerDiagonalRight.java
Проинициализируем их в конструкторе Game:
Победителя проверяем после каждого хода. Добавим кода в метод onClick() класса Listener
Метод gameOver() реализован в 2-х вариантах:
Для Java, gameOver(Player player) и gameOver() — разные методы. Воспользовавшись Builder’ом Toast.makeText, можно быстро создать и показать уведомление. refresh() обновляет состояние поля:
Готово! Надеюсь, эта статья помогла Вам освоиться в мире разработки под OS Android. Благодарю за внимание!
Создание приложений для Android — старт для начинающих
Разработка мобильного программного обеспечения может стать интересным и полезным занятием. В этой статье мы расскажем, как создать приложение для Android .
Android Studio — создание приложения
Чтобы написать приложение, нужно будет загрузить и установить Android Studio . В комплект поставки входит пакет разработки программного обеспечения со всеми библиотеками и кодами Android , необходимыми для разработки приложения. А также эмулятор Android , позволяющий сначала протестировать приложение на своем ПК, не устанавливая его на реальном мобильном устройстве.
Но сначала нужно загрузить и установить Java Development Kit ( JDK ) от Oracle . Найдите раздел « Java SE Development Kit 7u79 » и загрузите версию для своего ПК. Важно загрузить правильную версию ( 32-разрядную или 64-разрядную ), иначе Android Studio не сможет найти Java Runtime Environment ( JRE ).
Примечание: Oracle не будет публиковать на своих общедоступных сайтах какие-либо обновления Java SE 7 , и предполагается, что пользователи массово перейдут на Java 8 . Но в настоящий момент Android Studio требует наличия Java 7 . Это может измениться в будущем.
После того, как вы установили JDK , нужно инсталлировать Android Studio . Во время установки необходимо указать, сколько памяти зарезервировать для эмулятора Android . Он запускает Android в виде виртуальной машины, как смартфон с процессором Intel . Это быстрее, чем эмуляция процессора ARM на ПК. Но для запуска этой виртуальной машины эмулятор должен выделить некоторый объем памяти. Но перед тем как создать приложение для Андроид самому, имейте в виду, что сочетание Android Studio , Java и эмулятора будет довольно ресурсоемким, и компьютер может подтормаживать.
Google говорит, что необходимо как минимум 2 ГБ оперативной памяти, а рекомендуется 4 ГБ. Но мой основной ПК имеет 8 ГБ, и все равно иногда тормозит:
При первом запуске Android Studio выполнит первичную инициализацию, включающую в себя загрузку и установку актуальной версии Android SDK . Это может занять несколько минут.
Когда все будет загружено и установлено, вы увидите меню, которое позволит создать новый, открыть существующий или импортировать проект и т. д.
Разработка приложений для Android — cоздаем новый проект
Нажмите « Start a new Android Studio project » и введите название своего приложения в поле « Application name ». В поле « Company Domain » введите официальный домен вашей компании. Если вы независимый разработчик или любитель, введите собственный домен. Если вы просто экспериментируете с Android и не собираетесь в ближайшее время публиковать свои приложения в Google Play , просто оставьте пример домена, только измените « user » на ваше имя ( без пробелов ):
В следующем диалоговом окне проверьте, чтобы у вас выбрана опция « Phone and Tablet », а для « Minimum SDK » установлено — API 15: Android 4.0.3. Для опций « Wear » и « TV » флажки не должны быть установлены.
В диалоговом окне « Add an activity to Mobile » оставьте значение по умолчанию « Blank Activity » и нажмите « Next ». В диалоговом окне « Customize the Activity » оставьте все значения и нажмите « Finish »:
Интегрированная среда разработки ( IDE ) запущена. Это может занять несколько минут ( особенно, если вы впервые создали проект ). Если при запуске IDE увидите сообщение об ошибке « Rendering Problems: Rendering failed with known bug », нажмите ссылку « rebuild », которая отображается рядом с сообщением об ошибке.
По умолчанию, рабочее пространство среды IDE делится на три основные части ( не считая панели инструментов и т. д. ). Слева сверху находится дерево проекта. Справа от него — редактор кода, а под ними сообщения.
Перед тем, как создать приложение для Андроид с нуля, уже можно скомпилировать и запустить автоматически созданное приложение, но это не очень интересно. Вместо этого мы добавим несколько мелочей, чтобы вы познакомились с разработкой Android-приложений .
Как сделать приложение для андроид — дерево проекта
Дерево проекта содержит все файлы и ресурсы, необходимые для создания Android-приложения . Если вы знакомы с написанием простых программ на Java , C , Python и т. д., то могли бы подумать, что все будет содержаться только в одном или двух файлах. Но разработка Android-приложений немного сложнее:
В узле « app » дерева проектов содержится несколько узлов ( например, папки ), которые можно развернуть. Узлами верхнего уровня являются “ manifests ”, “ java ” и “ res ”. Последний — это сокращение от “ resources ”.
В “ manifests ” располагается файл « AndroidManifest.xml », каждое приложение должно содержать его. Это XML-файл с информацией о приложении, включая его название. Часто добавляемым в этот файл элементом является список разрешений, необходимых для приложения. Для этого простого приложения не нужно здесь ничего менять.
В разделе « java » располагается Java-код приложения. Он будет находиться в подкаталоге, с именем com.example.user.myfirstapp . Это имя домена компании, которое вы ввели ранее, только наоборот, плюс название приложения. В этой папке находится файл MainActivity.java . Это точка входа в приложение и единственный файл Java , который нам понадобится.
Продолжаем создавать простое приложение для Андроид . В разделе « res » есть несколько папок для графики, меню и элементов пользовательского интерфейса. Нас интересуют « layout » и « values ». В папке « layout » находится файл под названием « activity_main.xml ». Это XML-файл , описывающий пользовательский интерфейс. Редактировать его можно двумя способами. Первый — непосредственное редактирование XML-кода , второй — использование встроенного дизайнера пользовательского интерфейса:
В папке « values » содержатся несколько XML-файлов . В данный момент наиболее важным для нас является strings.xml . Вместо того чтобы задавать в Java-коде строковые значения их принято помещать в файл « strings.xml », и мы можем ссылаться на них через идентификаторы. Преимущество заключается в том, что если строка используется несколько раз, ее можно изменить только один раз, и изменения вступят в силу во всех местах. Это также упрощает поддержку нескольких языков в приложении.
Чтобы создать приложение для Андроид самому, нужно будет изменить файлы MainActivity.java , activity_main.xml и strings.xml .
Как сделать свое приложение для Android — написание приложения
Для нашего примера мы добавим кнопку с меткой « Tap Me! », изменим приветствие по умолчанию « Hello world! » на « Tap me if you dare! ». А также поменяем его, чтобы оно находилась в центре. И добавим код, чтобы при нажатии кнопки отображался текст « toast »!
Начнем с изменения текста приветствия и его выравнивания. Сначала найдите в дереве проекта файл « activity_main.xml » и дважды кликните по нему. Помните, что « activity_main.xml » — это файл, который содержит определение пользовательского интерфейса. В нижней части окна кода есть две вкладки: « Design » и « Text ». Перейдите на вкладку « Design ».
Теперь нажмите на текст « Hello world! », который показан в окне предварительного просмотра экрана смартфона. Если он слишком мал, используйте кнопку масштабирования ( лупа со значком «плюс» ).
В окне свойств, расположенном справа от изображения телефона, прокрутите экран вниз до тех пор, пока не найдете надпись « layout: centerInParent ». Кликните по пробелу рядом с ней и выберите « horizontal ». После этого текст « Hello world! » переместится в центр:
Перед тем, как создать приложение для Android без навыков, изменим текст. Строка « Hello world! » хранится в файле « strings.xml » в разделе res-> values . Если вы дважды кликните по этому файлу, то увидите несколько строк XML , которые определяют строки, используемые приложением.
Найдите эту строку:
И измените ее на:
Мы изменили выравнивание приветствия и его текст. Теперь добавим кнопку. Вернитесь на вкладку « Design » файла « activity_main.xml », найдите в списке « Palette » слева от изображения смартфона пункт « Button » и нажмите на него. Теперь кликните где-нибудь под надписью « Tap me if you dare! ».
Дважды кликните по кнопке, чтобы изменить ее текст. В конце поля “ text: ” расположена кнопка с тремя точками, нажмите на нее. В окне « Resources » нажмите « New Resource », а затем « New String Value… ». В поле « Resource name: » введите « tapme », а в поле « Resource value: » — “ Tap me! ”. Затем нажмите « ОК ». Теперь у нас есть кнопка “ Tap me! ”.
Последний шаг создания простого приложения для Андроид — добавить Java-код , который реагирует на нажатие кнопки. Один из элементов пользовательского интерфейса Android — это “ toast. ”. Он предоставляет простое сообщение в небольшом всплывающем окне. Вы, несомненно, видели это. Например, в Gmail при выходе из электронной почты до отправки письма выводится сообщение « Сообщение сохранено в черновики ». Спустя определенное время оно исчезает.
Для нашего примера приложения мы будем отображать сообщение каждый раз, когда нажимается кнопка. Первым шагом является добавление Java-кода . Найдите файл » MainActivity.java » и добавьте следующий код в » onCreate «:
Слово « View » во фразе «( View v )» будет красным, рядом с ним отображается сообщение, что вы использовали новую конструкцию ( View ), не импортируя ее в разделе импорта, в верхней части Java-кода . Это легко исправить. Нажмите на слово « View », а затем ALT + ENTER . Если слово “ Toast ” отмечено красным цветом, проделайте то же самое еще раз:
Вернитесь в раздел конструктора файла « activity_main.xml », нажмите кнопку и прокрутите список свойств до пункта « onClick ». Нажмите на поле справа, и на экране появится список функций. Кликните по « onButtonTap », это функция, которую мы только что добавили.
Теперь функция onButtonTap() будет вызываться всякий раз, когда будет нажиматься кнопка. Чтобы вывести сообщение, мы вызываем myToast.show() .
Вот и все, что касается создания приложения для Андроид самому, теперь протестируем его в эмуляторе.
Создание приложения для андроид — построение и тестирование
В меню « Tools » перейдите к Android- AVD Manager . Этот инструмент отображает список текущих настроенных виртуальных Android-устройств . У вас будет одно устройство, настроенное по умолчанию, возможно, Nexus 5 . Нажмите на значок воспроизведения ( треугольник ) в столбце « actions ». Это запустит эмулятор.
В зависимости от производительности вашего ПК и объема выделенной памяти запуск эмулятора может занять несколько минут. После того, как эмулятор будет запущен, перейдите в меню « Tools » и нажмите « Run ‘app ». Приложение будет скомпилировано и отправлено в эмулятор. Во время этого Android Studio спросит вас, какой эмулятор использовать. Вы увидите в списке свой текущий эмулятор. Это должна быть опция по умолчанию, поэтому просто нажмите « OK »:
Приложение появится в эмуляторе. Нажмите кнопку “ Tap me! ” — в нижней части экрана должно появиться сообщение. Поздравляю, все работает!
Что делать дальше и заключение
Также можно запустить приложение на реальном устройстве. Самый простой способ сделать это — включить USB-отладку на Android -устройстве и подключить его к компьютеру. Опцию отладки по USB можно найти в разделе Настройки – Для разработчиков . Если у вас нет этого раздела, откройте « Настройки » — « О телефоне », а затем нажмите « Номер сборки » семь раз.
Когда устройство будет подключено, нажмите « Run ‘app » в меню « Tools », но на этот раз не отправляйте приложение на виртуальное устройство, а отправьте на реальное устройство. Если устройство отсутствует в списке, это означает, что вы не включили отладку по USB или необходимо установить соответствующий USB-драйвер . Смотрите разделы USB-драйверы OEM и USB-драйвера Google в документации Google.
Вы успешно создали простое приложение для Андроид . Следующее, что нужно сделать, это написать второе приложение и продолжить работу. Google предоставляет много учебных материалов для Android-разработчиков , а также обширную документацию и множество примеров кода .
1.1: Your first Android app
This chapter describes how to develop applications using Android Studio, which is an integrated development environment (IDE) for Android.
The development process
An Android app project begins with an idea and a definition of the requirements necessary to realize that idea. You may want to sketch user interfaces (UIs) for the various app functions. To show what a UI would look like and how it would work, use drawings, mockups, and prototypes.
When you are ready to start coding, you use Android Studio to go through the following steps:
- Create the project in Android Studio and choose an appropriate template.
- Define a layout for each screen that has UI elements. You can place UI elements on the screen using the layout editor, or you can write code directly in the Extensible Markup Language (XML).
- Write code using the Java programming language. Create source code for all of the app's components.
- Build and run the app on real and virtual devices. Use the default build configuration or create custom builds for different versions of your app.©
- Test and debug the app's logic and UI.
- Publish the app by assembling the final APK (package file) and distributing it through channels such as Google Play.
Using Android Studio
Android Studio provides a unified development environment for creating apps for all Android-powered devices. Android Studio includes code templates with sample code for common app features, extensive testing tools and frameworks, and a flexible build system.
Starting an Android Studio project
After you have successfully installed the Android Studio IDE, double-click the Android Studio application icon to start it. Click Start a new Android Studio project in the Welcome window, and name the project the same name that you want to use for the app.
When choosing a unique Company domain, keep in mind that apps published to Google Play must have a unique package name. Because domains are unique, prepending the app's name with your name, or your company's domain name, should provide an adequately unique package name. If you don't plan to publish the app, you can accept the default example domain. Be aware that changing the package name later is extra work.
Choosing target devices and the minimum SDK
When choosing Target Android Devices, Phone and Tablet are selected by default, as shown in the figure below. The choice shown in the figure for the Minimum SDK—API 15: Android 4.0.3 (IceCreamSandwich)—makes your app compatible with 97% of Android-powered devices active on the Google Play Store.
Different devices run different versions of the Android system, such as Android 4.0.3 or Android 4.4. Each successive version often adds new APIs not available in the previous version. To indicate which set of APIs are available, each version specifies an API level. For instance, Android 1.0 is API level 1 and Android 4.0.3 is API level 15.
The Minimum SDK declares the minimum Android version for your app. Each successive version of Android provides compatibility for apps that were built using the APIs from previous versions. That means your app should always be compatible with future versions of Android, if you use the documented Android APIs.
Choosing an Activity template
An Activity is a single, focused thing that the user can do. It is a crucial component of any Android app. An Activity typically has a layout associated with it that defines how UI elements appear on a screen.
Android Studio pre-populates your project with minimal code for an Activity and layout based on a template. Available Activity templates range from a virtually blank template (Add No Activity) to an Activity that includes navigation and an options menu.
You can customize the Activity after you select your template. For example, the Empty Activity choice provides a single Activity with a single layout resource for the screen. The Configure Activity screen appears after you click Next. On the Configure Activity screen you can accept the commonly used name for the Activity (such as MainActivity ), or you can change the name.
Tip: This course covers the Activity class in more detail in another practical. You can also read Introduction to Activities for a comprehensive introduction.
The Configure Activity screen differs depending on which template you chose. In most cases you can select the following options, if they are not already selected:
- Generate Layout file: Leave this checkbox selected to create the layout resource connected to this Activity , which is usually named activity_main . The layout defines the UI for the Activity .
- Backwards Compatibility (AppCompat): Leave this checkbox selected to include the AppCompat library. Use the AppCompat library to make sure that the app is compatible with previous versions of Android, even if the app uses features found only in newer Android versions.
Android Studio creates a folder for your projects, and builds the project with Gradle.
Tip: See the Configure your build developer page for detailed information.
Exploring a project
An Android Studio project contains all of the source code and all resources for an app. The resources include layouts, strings, colors, dimensions, and images. The Android Studio main window is made up of several logical areas, or panes, as shown in the figure below.
In the figure above:
- Toolbar: Provides a wide range of actions, including running the Android app and launching Android tools.
- Navigation bar: Navigate through the project and open files for editing.
- Project pane: Displays project files in a hierarchy. The selected hierarchy in the figure above is Android.
- Editor: The contents of a selected file in the project. For example, after you select a layout (as shown in the figure above), the editor pane shows the layout editor with tools to edit the layout. After you select a Java code file, the editor pane shows the Java code with tools for editing the code.
- Tabs along the left, right, and bottom of the window: You can click tabs to open other panes, such as Logcat to open the Logcat pane with log messages, or TODO to manage tasks.
The status bar at the bottom of the Android Studio window displays the status of the project and Android Studio itself, as well as any warnings or messages. You can watch the build progress in the status bar.
Tip: You can organize the main window to give yourself more screen space by hiding or moving panes. You can also use keyboard shortcuts to access most features. See Keyboard Shortcuts for a complete list.
Using the Project pane
You can view the project organization in several ways in the Project pane. If it is not already selected, click the Project tab. (The Project tab is in the vertical tab column on the left side of the Android Studio window.)
The Project pane appears. To view the project in the standard Android project hierarchy, select Android from the Down arrow at the top of the Project pane.
Gradle files
When you first create an app project, the Project > Android pane appears with the Gradle Scripts folder expanded as shown below. If the Gradle Scripts folder is not expanded, click the triangle to expand it. This folder contains all the files needed by the build system.
The build.gradle(Module:app) file specifies additional libraries and the module's build configuration. The Activity template that you select creates this file. The file includes the minSdkVersion attribute that declares the minimum version for the app, and the targetSdkVersion attribute that declares the highest (newest) version for which the app has been optimized.
This file also includes a list of dependencies, which are libraries required by the code—such as the AppCompat library for supporting a wide range of Android versions.
App code
To view and edit the Java code, expand the app folder, the java folder, and the com.example.android.helloworld folder. Double-click the MainActivity java file to open it in the code editor.
The java folder includes Java class files. Each Activity , Service , or other component (such as a Fragment ) is defined as a Java class, usually in its own file. Tests and other Java class files are also located here.
The java folder contains three subfolders:
- com.example.hello.helloworld (or the domain name you have specified): All the files for a package are in a folder named after the package. For your Hello World app, there is one package, and it contains only MainActivity.java . The first Activity (screen) that the user sees, which also initializes app-wide resources, is customarily called MainActivity . (The file extension is omitted in the Project > Android pane.)
- com.example.hello.helloworld(androidTest) : This folder is for your instrumented tests, and starts out with a skeleton test file.
- com.example.hello.helloworld(test) : This folder is for your unit tests and starts out with an automatically created skeleton unit test file.
Layout files
To view and edit a layout file, expand the res folder and the layout folder to see the layout file. In the figure below, the layout file is called activity_main.xml .
Double-click the file to open it in the layout editor. Layout files are written in XML.
Resource files
The res folder holds resources, such as layouts, strings, and images. An Activity is usually associated with a layout of UI views that are defined as an XML file. This XML file is usually named after its Activity . The res folder includes these subfolders:
- drawable : Store all your app's images in this folder.
- layout : Every Activity has at least one XML layout file that describes the UI. For Hello World, this folder contains activity_main.xml .
- mipmap : The launcher icons are stored in this folder. There is a subfolder for each supported screen density. Android uses the screen density (the number of pixels per inch) to determine the required image resolution. Android groups all actual screen densities into generalized densities, such as medium (mdpi), high (hdpi), or extra-extra-extra-high (xxxhdpi). The ic_launcher.png folder contains the default launcher icons for all the densities supported by your app.
- values : Instead of hardcoding values like strings, dimensions, and colors in your XML and Java files, it is best practice to define them in their respective values files. This practice makes it easier to change the values and keep the values consistent across your app.
The values subfolder includes these subfolders:
- colors.xml : Shows the default colors for your chosen theme. You can add your own colors or change the colors based on your app's requirements.
- dimens.xml : Store the sizes of views and objects for different resolutions.
- strings.xml : Create resources for all your strings. Doing this makes it easy to translate the strings to other languages.
- styles.xml : All the styles for your app and theme go here. Styles help give your app a consistent look for all UI elements.
Using the editor pane
If you select a file, the editor pane appears. A tab appears for the file so that you can open multiple files and switch between them. For example, if you double-click the activity_main.xml layout file in the Project > Android pane, the layout editor appears as shown below.
If you double-click the MainActivity file in the Project > Android pane, the editor changes to the code editor as shown below, with a tab for MainActivity.java:
At the top of the MainActivity.java file is a package statement that defines the app package. This package statement is followed by an import block condensed with . , as shown in the figure above. Click the dots to expand the block to view it. The import statements import libraries needed for the app. For example, the following statement imports the AppCompatActivity library:
Each Activity in an app is implemented as a Java class. The following class declaration extends the AppCompatActivity class to implement features in a way that is backward-compatible with previous versions of Android:
Understanding the Android manifest
Before the Android system can start an app component such as an Activity , the system must know that the Activity exists. It does so by reading the app's AndroidManifest.xml file, which describes all of the components of your Android app. Each Activity must be listed in this XML file, along with all components for the app.
To view and edit the AndroidManifest.xml file, expand the manifests folder in the Project > Android pane, and double-click AndroidManifest.xml . Its contents appear in the editing pane:
Android namespace and application tag
The Android Manifest is coded in XML and always uses the Android namespace:
The package expression shows the unique package name of the new app. Do not change the package expression after the app is published.
The <application> tag, with its closing </application> tag, defines the manifest settings for the entire app.
Automatic backup
The android:allowBackup attribute enables automatic app data backup:
Setting the android:allowBackup attribute to true enables the app to be backed up automatically and restored as needed. Users invest time and effort to configure apps. Switching to a new device can cancel out all that careful configuration. The system performs this automatic backup for nearly all app data by default, and does so without the developer having to write any additional app code.
For apps whose target SDK version is Android 6.0 (API level 23) and higher, devices running Android 6.0 and higher automatically create backups of app data to the cloud because the android:allowBackup attribute defaults to true if omitted. For apps < API level 22 you have to explicitly add the android:allowBackup attribute and set it to true .
Tip: To learn more about the automatic backup for apps, see Configuring Auto Backup for Apps.
The app icon
The android:icon attribute sets the icon for the app:
The android:icon attribute assigns to the app an icon in the mipmap folder (inside the res folder in the Project > Android pane). The icon appears on the home screen or in the Search Apps screen for launching the app. The icon is also used as the default icon for app components.
App label and string resources
The android:label attribute shows the string "Hello World" highlighted. If you click the string, it changes to show the string resource @string/app_name :
Tip: To see the context menu, ctrl-click or right-click app_name in the editor pane. Select Go To > Declaration to see where the string resource is declared: in the strings.xml file. When you select Go To > Declaration or open the file by double-clicking strings.xml inside the values folder in the Project > Android pane, the file's contents appear in the editor pane.
After opening the strings.xml file, you can see that the string name app_name is set to Hello World . You can change the app name by changing the Hello World string to something else. String resources are described in a separate lesson.
App theme
The android:theme attribute sets the app's theme, which defines the appearance of UI elements such as text:
The theme attribute is set to the standard theme AppTheme . Themes are described in a separate lesson.
Declaring the Android version
Different devices may run different versions of the Android system, such as Android 4.0 or Android 4.4. Each successive version can add new APIs not available in the previous version. To indicate which set of APIs are available, each version specifies an API level. For instance, Android 1.0 is API level 1 and Android 4.4 is API level 19.
The API level allows a developer to declare the minimum version with which the app is compatible, using the <uses-sdk> manifest tag and its minSdkVersion attribute. For example, the Calendar Provider APIs were added in Android 4.0 (API level 14). If your app can't function without these APIs, declare API level 14 as the app's minimum supported version like this:
The minSdkVersion attribute declares the minimum version for the app, and the targetSdkVersion attribute declares the highest (newest) version which has been optimized within the app. Each successive version of Android provides compatibility for apps that were built using the APIs from previous versions, so the app should always be compatible with future versions of Android while using the documented Android APIs.
The targetSdkVersion attribute does not prevent an app from being installed on Android versions that are higher (newer) than the specified value. Even so, the target attribute is important, because it indicates to the system whether the app should inherit behavior changes in newer versions.
If you don't update the targetSdkVersion to the latest version, the system assumes that your app requires backward-compatible behaviors when it runs on the latest version. For example, among the behavior changes in Android 4.4, alarms created with the AlarmManager APIs are now inexact by default so that the system can batch app alarms and preserve system power. If your target API level is lower than "19" , the system retains the previous API's behavior for your app.
Understanding the build process
The Android application package (APK) is the package file format for distributing and installing Android mobile apps. The build process involves tools and processes that automatically convert each project into an APK.
Android Studio uses Gradle as the foundation of the build system, with more Android-specific capabilities provided by the Android Plugin for Gradle. This build system runs as an integrated tool from the Android Studio menu.
Understanding build.gradle files
When you create a project, Android Studio automatically generates the necessary build files in the Gradle Scripts folder in the Project > Android pane. Android Studio build files are named build.gradle as shown below:
build.gradle (Project: apptitle)
This file is the top-level build file for the entire project, located in the root project folder, which defines build configurations that apply to all modules in your project. This file, generated by Android Studio, should not be edited to include app dependencies.
If a dependency is something other than a local library or file tree, Gradle looks for the files in whichever online repositories are specified in the repositories block of this file. By default, new Android Studio projects declare JCenter and Google (which includes the Google Maven repository) as the repository locations:
build.gradle (Module: app)
Android Studio creates separate build.gradle (Module: app) files for each module. You can edit the build settings to provide custom packaging options for each module, such as additional build types and product flavors, and to override settings in the manifest or top-level build.gradle file. This file is most often the file to edit when changing app-level configurations, such as declaring dependencies in the dependencies section. The following shows the contents of a project's build.gradle (Module: app) file:
The build.gradle files use Gradle syntax. Gradle is a Domain Specific Language (DSL) for describing and manipulating the build logic using Groovy, which is a dynamic language for the Java Virtual Machine (JVM). You don't need to learn Groovy to make changes, because the Android Plugin for Gradle introduces most of the DSL elements you need.
Tip: To learn more about the Android plugin DSL, read the DSL reference documentation.
Plugin and Android blocks
In the build.gradle (Module: app) file above, the first statement applies the Android-specific Gradle plug-in build tasks:
The android < >block specifies the target SDK version for compiling the app code ( compileSdkVersion 26 ) and several blocks of information.
The defaultConfig block
Core settings and entries for the app are specified in the defaultConfig < >block within the android < >block:
The minSdkVersion and targetSdkVersion settings override any AndroidManifest.xml settings for the minimum SDK version and the target SDK version. See "Declaring the Android version" previously in this chapter for background information on these settings.
The testInstrumentationRunner statement adds the instrumentation support for testing the UI using Espresso and UIAutomator. These tools are described in a separate lesson.
Build types
Build types for the app are specified in a buildTypes < >block, which controls how the app is built and packaged.
The build type specified is release for the app's release. Another common build type is debug . Configuring build types is described in a separate lesson.
Dependencies
Dependencies for the app are defined in the dependencies < >block, which is the part of the build.gradle file that is most likely to change as you start developing code that depends on other libraries. The block is part of the standard Gradle API and belongs outside the android < >block.
In the snippet above, the statement implementation fileTree(dir: 'libs', include: ['*.jar']) adds a dependency of all ".jar" files inside the libs folder.
Syncing your project
When you make changes to the build configuration files in a project, Android Studio requires that you sync the project files. During the sync, Android Studio imports the build configuration changes and runs checks to make sure the configuration won't create build errors.
To sync the project files, click Sync Now in the notification bar that appears when making a change (as shown in the figure below), or click the Sync Project with Gradle Files button in the menu bar.
If Android Studio notices any errors with the configuration — for example, if the source code uses API features that are only available in an API level higher than the compileSdkVersion —the Messages window appears to describe the issue.
Running the app on an emulator or a device
With virtual device emulators, you can test an app on different devices such as tablets or smartphones—with different API levels for different Android versions—to make sure it looks good and works for most users. You don't have to depend on having a physical device available for app development.
The Android Virtual Device (AVD) manager creates a virtual device or emulator that simulates the configuration for a particular type of Android-powered device. Use the AVD Manager to define the hardware characteristics of a device and its API level, and to save it as a virtual device configuration. When you start the Android emulator, it reads a specified configuration and creates an emulated device on your computer that behaves exactly like a physical version of that device.
Creating a virtual device
To run an emulator on your computer, use the AVD Manager to create a configuration that describes the virtual device. Select Tools > Android > AVD Manager, or click the AVD Manager icon in the toolbar.
The Your Virtual Devices screen appears showing all of the virtual devices created previously. Click the +Create Virtual Device button to create a new virtual device.
You can select a device from a list of predefined hardware devices. For each device, the table provides a column for its diagonal display size (Size), screen resolution in pixels (Resolution), and pixel density (Density). For example, the pixel density of the Nexus 5 device is xxhdpi , which means the app uses the icons in the xxhdpi folder of the mipmap folder. Likewise, the app uses layouts and drawables from folders defined for that density.
After you click Next, the System Image screen appears for choosing the version of the Android system for the device. The Recommended tab shows the recommended systems for the device. More versions are available under the x86 Images and Other Images tabs. If a Download link is visible next to a system image version, it is not installed yet. Click the link to start the download, and click Finish when it's done.
Running the app on the virtual device
To run the app on the virtual device you created in the previous section, follow these steps:
In Android Studio, select Run > Run app or click the Run icon in the toolbar.
In the Select Deployment Target window, under Available Emulators, select the virtual device you created, and click OK.
The emulator starts and boots just like a physical device. Depending on the speed of your computer, the startup process might take a while. The app builds, and once the emulator is ready, Android Studio uploads the app to the emulator and runs it.
You should see the app created from the Empty Activity template ("Hello World") as shown in the following figure, which also shows Android Studio's Run pane that displays the actions performed to run the app on the emulator.
Tip: When testing on a virtual device, it is a good practice to start it up once, at the very beginning of your session. Do not close it until you are done testing your app, so that your app doesn't have to go through the device startup process again. To close the virtual device, select Quit from the menu or press Control-Q in Windows or Command-Q in macOS.
The figure above shows the emulator and the run log:
- The Emulator running the app.
- The Run pane, which shows the actions taken to install and run the app.
- The Run tab, which you click to open or close the Run pane.
Running the app on a physical device
Always test your apps on a physical device. While emulators are useful, they can't show all possible device states, such as what happens if an incoming call occurs while the app is running. To run the app on a physical device, you need the following:
- An Android-powered device such as a phone or tablet.
- A data cable to connect your Android-powered device to your computer via the USB port.
- If you are using a Linux or Windows system, you may need to perform additional steps to run on a hardware device. Check the Using Hardware Devices documentation. You may also need to install the appropriate USB driver for your device. See OEM USB Drivers.
To let Android Studio communicate with your Android-powered device, you must turn on USB Debugging on the device. You enable USB Debugging in the device's Developer options settings. (Note that enabling USB Debugging is not the same as rooting your device.)
On Android 4.2 and higher, the Developer options screen is hidden by default. To show developer options and enable USB Debugging:
- On your device, open Settings > About phone and tap Build number seven times.
- Return to the previous screen (Settings). Developer options appears at the bottom of the list. Tap Developer options.
- Select USB Debugging.
- Connect the device and run the app from Android Studio.
Using the log
The log is a powerful debugging tool you can use to look at values, execution paths, and exceptions. After you add logging statements to an app, your log messages appear along with general log messages in the Logcat pane.
Viewing log messages
To see the Logcat pane, click the Logcat tab at the bottom of the Android Studio window as shown in the figure below.
In the figure above:
- The Logcat tab for opening and closing the Logcat pane, which displays information about your app as it is running. If you add Log statements to your app, Log messages appear here.
- The Log level menu set to Verbose (the default), which shows all Log messages. Other settings include Debug, Error, Info, and Warn.
Adding logging statements to your app
Logging statements add whatever messages you specify to the log. Adding logging statements at certain points in the code allows the developer to look at values, execution paths, and exceptions. For example, the following logging statement adds "MainActivity" and "Hello World" to the log:
The following are the elements of this statement:
- Log : The Log class for sending log messages to the Logcat pane.
- d : The Debug Log level setting to filter log message display in the Logcat pane. Other log levels are e for Error, w for Warn, and i for Info. You assign a log level so that you can filter the log messages using the drop-down menu in the center of the Logcat pane.
- "MainActivity" : The first argument is a tag which can be used to filter messages in the Logcat pane. This tag is commonly the name of the Activity from which the message originates. However, you can name the tag anything that is useful to you for debugging.
- "Hello world" : The second argument is the actual message.
By convention, log tags are defined as constants for the Activity :
Use the constant in the logging statements:
After you add the Log.d statement shown above, follow these steps to see the log message: