My First App: How to Create Your First Android App Step by Step
To create a native Android app, one that can directly use all the features and functionality available on an Android phone or tablet, you need to use the Android platform’s Java API framework. This is the API that allows you to perform common tasks such as drawing text, shapes, and colors on the screen, playing sounds or videos, and interacting with a device’s hardware sensors. Over the years, the Android API framework has evolved to become more stable, intuitive, and concise. As a result, being an Android developer today is easier than ever—even more so if you use Android Studio, the official tool for working with the framework.
In this tutorial, I’ll show you how to create your first Android app. While doing so, I’ll also introduce you to important Android-specific concepts such as views, layouts, and activities.
We’ll be starting from scratch to create a very simple app in this tutorial. If you prefer writing less code or need to develop your app as quickly as possible, however, consider using one of the native Android app templates available on CodeCanyon.
Using an app template, you can have a polished, ready-to-publish app in just a matter of hours. You can learn how to use an Android app template by referring to the following tutorial:
Prerequisites
To be able to follow along, you’ll need:
- the latest version of Android Studio
- a device or emulator running Android Marshmallow or higher
If you don’t have Android Studio, do refer to the following tutorial to learn how to install and configure it:
1. Create a New Project
You’ll need an Android Studio project to design, develop, and build your app. So launch Android Studio and click on the Start a new Android Studio project button.
On the next screen, choose Add No Activity because we don’t want to use any of the templates offered by Android Studio. Then press Next to proceed.
You’ll now see a form where you can enter important details about your app, such as its name and package name. The name is, of course, the name your users will see on their phones when they install your app.
The package name, on the other hand, is a unique identifier for your app on Google Play. You must follow the Java package naming conventions while specifying it. For example, if your app’s name is MyFirstApp and you work for an organization whose website address is example.com, the package name would ideally be «com.example.myfirstapp».
Next, you must decide the programming language you want to use while coding the app. For now, select Java and press Finish.
Android Studio will now take a minute or two to generate and configure the project.
2. Create an Activity
An activity is one of the most important components of an Android app. It is what allows you to create and display a user interface to your users. An app can have one or more activities, each allowing the user to perform an action. For example, an email client app can have three activities: one for the user to sign up, one to sign in, and one to compose an email.
To keep this tutorial simple, we’ll be creating an app with just one activity. To create the activity, in the Project panel of Android Studio, right-click on app and select New > Activity > Empty Activity.
In the dialog that pops up, type in MainActivity as the name of the activity, check the Launcher Activity option, and press Finish.
Checking the Launcher Activity option is important because it is what allows your users to open the activity using an Android launcher. As such, a launcher activity serves as an entry point to your app.
3. Create a Layout
Each activity usually has at least one layout associated with it. When you created your activity in the previous step, you also generated an empty layout for it. To take a look at it, open the activity_main.xml file.
An activity’s layout primarily consists of views and view groups. A view, sometimes referred to as a widget, is an individual component of your user interface. Buttons, text fields, labels, and progress bars are common examples of views. A view group is a component that can serve as a container for views. Usually, view groups also help you position and set the dimensions of your views.
ConstraintLayout is one of the most powerful and flexible view groups available today. By default, it is the root node of your activity’s layout XML file. It looks like this:
We’ll be creating a simple clock app in this tutorial. In addition to the local time, it will be able to show the current time in two different countries: India and Germany.
To allow the user to choose the country they’re interested in, our layout will have two Button views, one for Germany, and one for India. And to actually show the time, our layout will have a TextClock view.
Accordingly, add the following code inside the ConstraintLayout :
Note that each view must have the layout_width and layout_height properties. They decide how large the view is. Other properties such as layout_constraintBottom_toBottomOf and layout_constraintLeft_toLeftOf are necessary to position the view. With the above code, the TextClock view will be placed at the center of the screen, and both the Button views towards the bottom of the screen.
By default, the TextClock view only shows the hours and minutes. The format12Hour property, however, allows you to change that. In the above code, its value is set to h:mm:ss a . This tells the TextClock view that it should display the hours, minutes, seconds, and also an AM/PM suffix.
Also note that each Button view has an onClick property. This property is used to assign click event handlers to the buttons.
The handlers don’t exist yet, but you can ask Android Studio to generate them for you. To do so, hover over the name of the handler until you see a red light bulb appear beside it. Then click on the light bulb and select the second option, the one with the yellow light bulb.
At this point, you can try pressing Shift-F10 to run the app. If there are no errors in your XML code, you should see something like this on your phone or emulator:
Although the buttons don’t work yet, the TextClock view should show the local time, updating itself every second.
4. Implement Event Handlers
When you generated event handlers for the two buttons, Android Studio added two methods to your activity’s Java file, MainActivity.java. If you open it, you should find the following code in it:
Inside the event handlers, all we need to do is change the time zone of the TextClock view. But how do you reference a view that’s in your layout XML file from inside your Java file? Well, you just use the findViewById() method.
Once you have a reference to the TextClock view, you can call its setTimeZone() method to change its time zone. So add the following code inside the onClickGermany() method:
Similarly, add the following code inside the onClickIndia() method:
If you’re wondering what R is, it’s an auto-generated class that contains, among other things, the IDs of all the views you have in your layouts. The findViewById() method expects you to use this class while passing an ID to it.
At this point, you can press Shift-F10 again to re-run the app. You should now be able to click on the buttons to change the clock’s time zone.
Conclusion
You just created your first fully functional, native app for Android! I encourage you to make a few changes to it. For instance, you could try using other time formats or time zones. You could also try changing the positions of the buttons and the clock view.
There are dozens of views and view groups you can use to create your apps. Do refer to the official documentation to learn about them.
Android App Templates and UI Kits From CodeCanyon
You may have noticed that our app looks very plain and simple. That’s because we’re using the default theme, without applying any styles to our views. CodeCanyon is full of Android UI kits that offer beautiful, hand-crafted styles you can apply to your views.
The kits generally also have several custom views and layouts. You can refer to the following articles to learn more about them:
Источник
Android Development Tutorial. Часть 1/?
Ларс Вогель — евангелист Eclipse.
Под катом Вы обнаружите перевод его статьи, которая описывает процесс создания Android-приложений с помощью Eclipse. Используется Eclipse 3.6, Java 1.6 и Android 2.3 (Gingerbread).
Часть 2
1. Разработка под Android
1.1. Операционная система Android
Android — операционная система, основанная на Linux с интерфейсом программирования Java. Это предоставляет нам такие инструменты, как компилятор, дебаггер и эмулятор устройства, а также его (Андроида) собственную виртуальную машину Java (Dalvik Virtual Machine — DVM). Android создан альянсом Open Handset Alliance, возглавляемым компанией Google.
Android использует специальную виртуальную машину, так званую Dalvik Virtual Machine. Dalvik использует свой, особенный байткод. Следовательно, Вы не можете запускать стандартный байткод Java на Android. Android предоставляет инструмент «dx», который позволяет конвертировать файлы Java Class в файлы «dex» (Dalvik Executable). Android-приложения пакуются в файлы .apk (Android Package) программой «aapt» (Android Asset Packaging Tool) Для упрощения разработки Google предоставляет Android Development Tools (ADT) для Eclipse. ADT выполняет автоматическое преобразование из файлов Java Class в файлы dex, и создает apk во время развертывания.
Android поддерживает 2D и 3D графику, используя библиотеки OpenGL, а также хранение данных в базе данных SQLite.
Каждое Android-приложение запускается в своем собственном процессе и под своим собственным userid, который автоматически генерируется Android-ом во время развертывания. Поэтому приложение изолировано от других запущенных приложений, и неправильно работающее приложение не может беспрепятственно навредить другим Android-приложениям.
1.2. Основные компоненты Android
Android-приложения состоят из следующих частей:
- Activity/Деятельность (далее Активити) — представляет собой схему представления Android-приложений. Например, экран, который видит пользователь. Android-приложение может иметь несколько активити и может переключаться между ними во время выполнения приложения.
- Views/Виды — Пользовательский интерфейс активити, создаваемый виджетами классов, наследуемых от «android.view.View». Схема views управляется через «android.view.ViewGroups».
- Services/Службы — выполняет фоновые задачи без предоставления пользовательского интерфейса. Они могут уведомлять пользователя через систему уведомлений Android.
- Content Provider/Контент-провайдеры — предоставляет данные приложениям, с помощью контент-провайдера Ваше приложение может обмениваться данными с другими приложениями. Android содержит базу данных SQLite, которая может быть контент-провайдером
- Intents/Намерения (далее Интенты) — асинхронные сообщения, которые позволяют приложению запросить функции из других служб или активити. Приложение может делать прямые интенты службе или активити (явное намерение) или запросить у Android зарегистрированные службы и приложения для интента (неявное намерение). Для примера, приложение может запросить через интент контакт из приложения контактов (телефонной/записной книги) аппарата. Приложение регистрирует само себя в интентах через IntentFilter. Интенты — мощный концепт, позволяющий создавать слабосвязанные приложения.
- Broadcast Receiver/Широковещательный приемник (далее просто Приемник) — принимает системные сообщения и неявные интенты, может использоваться для реагирования на изменение состояния системы. Приложение может регистрироваться как приемник определенных событий и может быть запущено, если такое событие произойдет.
Другими частями Android являются виджеты, или живые папки (Live Folders), или живые обои (Live Wallpapers). Живые папки отображают источник любых данных на «рабочем столе» без запуска соответствующих приложений.
1.3. Безопасность и разрешения
Android определяет конкретные разрешения для определенных задач. К примеру, если приложение хочет получить доступ в Интернет, оно должно определить в своем файле конфигурации, что оно хотело бы получить соответствующие разрешения. Во время установки Android-приложения пользователю показывается экран, на котором ему нужно дать приложению требуемые разрешения.
1.4. AndroidManifest.xml
Android-приложения описываются файлом «AndroidManifest.xml». В этих файлах должны быть объявлены все активити, службы, приемники и контент-провайдеры приложения. Также он должен содержать требуемые приложением разрешения. Например, если приложению требуется доступ к сети, то это должно быть определено здесь. «AndroidManifest.xml» можно рассматривать, как описание для развертывания Android-приложения.
Атрибут «package» — базовый пакет для следующих элементов Java. Он также обязан быть уникальным, т.к. Android Marketplace только единожды принимает заявку на каждый «package». Следовательно, хорошей привычкой будет использование Вашего обратного доменного имени как «package», для избежания конфликтов с другими разработчиками.
«android:versionName» и «android:versionCode» определяют версию Вашего приложения. «versionName» — то, что видит пользователь и может быть любой строкой. «versionCode» должен быть целым, и Android Market использует это для определения, предоставили ли Вы новую версию, чтобы запустить обновления на устройствах, на которых установлено Ваше приложение. Как правило. начинается с 1 и увеличивается на единицу, если Вы выпускаете новую версию приложения.
«activity» определяет активити, в этом примере указывает на класс «de.vogella.android.temperature.Convert». Для этого класса зарегистрирован фильтр интентов, определяющий, что это активити запускается при запуске приложения (действие android:name=«android.intent.action.MAIN»). Определение категории (категория android:name=«android.intent.category.LAUNCHER» ) определяет, что это приложение добавлено в директорию приложений на Android-устройстве. Значения со знаком @ ссылаются на файлы ресурсов, которые содержат актуальные значения. Это упрощает работу с разными ресурсами, такими как строки, цвета, иконки, для разных устройств и упрощает перевод приложений.
Часть «uses-sdk» из «AndroidManifest.xml» определяет минимальную версию SDK, на котором можно запускать Ваше приложение. Это предотвращает установку Вашего приложения на устройства с более старой версией SDK.
1.5. R.java, Resources и Assets
Каталог «gen» в Android-проекте содержит генерированные значения. «R.java» — генерированный класс, который содержит ссылки на ресурсы из папки «res» проекта. Эти ресурсы содержатся в директории «res» и могут быть значениями, меню, схемами, иконками или рисунками, или анимациями. Например, ресурсом могут быть рисунок или XML-файлы, содержащие определенные строки.
Если Вы создаете новые ресурсы, то соответствующие ссылки будут автоматически созданы в «R.java». Ссылки являются статическими значениями типа int (целочисленными константами), система Android предоставляет методы доступа к соответствующим ресурсам. Например, для доступа к строке с идентификатором ссылки «R.string.yourString» используйте метод getString(R.string.yourString)); Пожалуйста, не пробуйте изменять «R.java» в ручную.
Тогда как каталог „res“ хранит структурированные значения, известные платформе Android, каталог „assets“ может быть использован для хранения любых данных. В Java Вы можете получить доступ к этим данным через AssetsManager и метод getAssets().
1.6. Активити и Макеты (layout)
Пользовательский интерфейс для деятельности (Activity) определяется с помощью макетов. Во время исполнения макеты — экземпляры «android.view.ViewGroups». Макет определяет элементы пользовательского интерфейса, их свойства и расположение. Элементы UI основываются на классе «android.view.View». ViewGroup — подкласс View. Макеты может содержать компоненты UI (Views/Виды) или другие макеты (ViewGroups). Вам не следует делать большую вложенность дочерних элементов во ViewGroups, так как это влияет на производительность.
Макет может быть определен с помощью Java-кода или с помощью XML. Как правило, используйте Java-код для генерирования макета, если не знаете про содержимое заранее. Например, если Ваш макет зависит от содержимого, которое Вы читаете из интернета.
Макеты, основанные на XML определяются с помощью файла ресурсов в папке «/res/layout». Этот файл определяет группу видов (см. пункт 1.2), виды, их отношения и атрибуты для отдельных макетов. Если элемент UI требует доступа с помощью Java-кода, дайте элементу UI уникальный идентификатор (id) с помощью атрибута «android:id». Для того, чтобы назначить новый идентификатор элементу UI, используйте конструкцию «@+id/yourvalue». Условно это создаст и назначит новый id «yourvalue» соответствующему элементу UI. Позже, в Java-коде Вы можете получить доступ к этим элементам UI с помощью метода findViewById(R.id.yourvalue).
Определение макетов через XML обычно предпочтительней, поскольку отделяет программной логику от определения макетов и позволяет легче определять разные ресурсы макетов, для разных устройств. Можно также смешивать оба подхода.
Источник