Въведение в средата за програмиране на Android приложения. Създаване и изпълнение на примерно приложение. / Introduction to the Android development environment. Creating and executing of demo application.
1. Въведение
- Целта на това практическо упражнение е да се усвоят основните стъпки от процеса по разработване на приложения за ОС Android – от създаването на празен проект до реализирането на примерно приложение и инсталацията му на емулирано устройство. По специално студентите ще придобият познания, за това, как да използват основните пособия от средата за разработване с цел поддръжката на процеса по създаване на приложения, както и основните компоненти на приложенията за Android.
2. Цел на упражнението
- Инсталиране и настройка на средата за разработване на приложения;
- Създаване на “Hello World” приложение за ОС Android;
- Обзор и анализ на отделните компоненти на проект за Android приложение;
- Използване на симулатор/емулатор за Android устройства;
3. Инсталиране и конфигуриране на работната среда
- Изтеглете и инсталирайте Android Studio. Използвайте интернет търсачка или следният адрес: link
- The aim of this lab exercise is to learn the basic steps of the process of developing applications for Android OS – from creating a blank project to the creation of a sample application and its installation on an emulated device. In particular, students will gain knowledge on how to use the basic tools of the development environment in order to support the process of creating applications. Students will learn the main components of Android applications.
2. Exercise goals
- Installation and setup of the Android development environment;
- Creating a “Hello World” application for Android;
- Overview and analysis of the individual components of the Android application project.
- Using a simulator/emulator for Android devices;
3.Installation and configuration of the development environment
- Download Android Studio and install it. Use Internet search engine or the following address to download Android Studio: link

- Използвайте настройките по подразбиране за инсталацията на Android Studio. Всички компоненти на работната среда трябва да бъдат маркирани.
- Use the default settings when installing Android Studio. All the components of the environment have to be marked for installation.

4. Разработване на примерно ”Hello World” приложение
4.1. Създаване на нов Android проект
4.1. Creating new Android project

- Стъпка 1. – Стартирайте Android Studio (ако вече не е стартирано).
Стъпка 2. – От визуализиралия се екран изберете “New project”.
Стъпка 3. – На следващия екран, изберете “Empty Activity”.
- Step 1. – Launch the Android Studio (if it is not already running).
Step 2. – From the screen that appears (Fig. 3), select “New project”.
Step 3. – On the next screen (Fig. 4), select “Empty Activity”.

- На следващия екран, въведете следните настройки за проекта и изберете Next:
- Name: Lab1
- Package name: com.example.lab1
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab1
- Language: Java
- Minimum SDK: API 19: Android 4.4 (KitKat)
Изборът на API 19 е за по-добра обратна съвместимост. Така ще бъдат покрити почти всички мобилни устройства, които все още се използват, въпреки старата версия на Android.
След това натиснете Finish. Android Studio автоматично ще генерира всички файлове и компоненти, които ще съдържа новото приложение. След завършването на този процес, ще се появи следния екран:
- On the next screen, enter the following project settings and select Next:
- Name: Lab1
- Package name: com.example.lab1
- Save location: C:\Users\your_username\AndroidStudioProjects\Lab1
- Language: Java
- Minimum SDK: API 19: Android 4.4 (KitKat)
Selecting API 19 is for better backward compatibility. This will cover almost all mobile devices that are still in use despite the old version of Android.
Then click Finish. Android Studio will automatically generate all the files and components that the new application will contain. After completing this process, the following window will appear:

- Разгледайте работната среда и се запознайте със всички прозорци и елементи.
4.2. Анализ на създаденото примерно приложение
- Приложението, което беше създадено се характеризира с типичната структура за всички приложения за ОС Android. Разгледайте лявата секция на средата за разработване и разтворете всички полета:
- manifests: Съдържа файла AndroidManifest.xml. Всеки проект съдържа един такъв файл в главната си директория. В този файл се съхранява цялата информация за приложението, която е необходима на ОС, за да го изпълни успешно:
- Наименование на пакета, което се използва за идентифициране на приложението.
- Списък на класовете за дейностите, услугите, приемниците и доставчиците на услуги, както и цялата информация, която им е необходима включително и правата за достъп.
- Системните права, които приложението трябва да дефинира, за да получи достъп до различни системни ресурси, като GPS и др.
- Права за достъп до приложението, с които други приложения трябва да разполагат, за да могат да си взаимодействат с него.
- Информация за профилите на приложението.
- Библиотеките и нивото на API, които приложението ще използва.Ако разгърнете тази секция ще видите йерархията на пакетите, които сте въвели. В тази секция ще се записват и файловете, които съдържат програмния код;
- java: Съдържа основните Java файлове, които се използват от операционната система за стартиране и управление на приложението. Това е автоматично генериран шаблонен клас на приложението, който носи името, което сте въвели при създаването на проекта. Този шаблонен клас може да бъде допълван с код по-късно. В текущия момент от време съдържа основните функции, които се изпълняват при пускане на приложението и при избор на елемент от менюто с настройки за приложението.
- res: Тази папка ще съдържа всички ресурси (т.е. вътрешните файлове с данни), които вашето приложение използва. Съществуват няколко основни вида ресурси, които се използват при програмирането и създаването на Android приложения и средата е създала отделна поддиректория за всеки от тях;
- drawable: В тази папка се съдържат изображения или анимации, които бихте могли да използвате във вашето приложение.
- layout: В тази папка се съхраняват xml файлове с шаблони. Приложенията използват тези файлове при изграждането на потребителските интерфейси.
- Explore the programing environment and get familiar with all the windows and elements.
4.2. Analysis of the created demo application
- The application that was created is with the typical structure for all Android applications. Take a look at the left section of the development environment and expand all the fields:
- manifests: Contains the AndroidManifest.xml file. Each project contains one such file in its root directory. This file stores all the information about the application that the OS needs to run it successfully:
- Package name which is used to identify the application.
- List of classes for activities, services, receivers and service providers, as well as all the information they need, including access rights.
- The system rights that the application must define in order to access various system resources, such as GPS, etc.
- Access rights to the application that other applications must have in order to interact with it.
- Application profile information.
- The libraries and API level that the application will use. If you expand this section you will see the hierarchy of the packages you have entered. The files containing the program code will also be saved in this section;
- java: Contains the main Java files used by the operating system to launch and manage the application. This is an automatically generated application template class that takes the name you entered when creating the project. This template class can be supplemented with code later. Currently contains the main functions that are performed when launching the application and when selecting an item from the settings menu for the application.
- res: This folder will contain all the resources (ie internal data files) that your application uses. There are several main types of resources used in programming and creating Android applications, and the environment has created a separate subdirectory for each;
- drawable: This folder contains images or animations that you can use in your application.
- layout: Xml template files are stored in this folder. Applications use these files to build user interfaces.

- Въпреки, че използването на шаблонен xml файл не е задължително, това е препоръчителният начин за изграждане на потребителските интерфейси за ОС Android. Можете да видите, че в папката вече съдържа един файл – activity_main.xml, който съдържа шаблона за потребителския интерфейс на приложението което създавате. Ако активирате шаблона (с двойно натискане върху него), той ще се зареди в редактора на графични интерфейси на работната среда, като по този начин ще ви позволи да го модифицирате чрез добавяне на елементи, като бутони, полета за извеждане и въвеждане на данни и т.н. Ако изберете таба Text ще можете да разгледате файла activity_main.xml като текст.
Както може би сте забелязали в този файл има дефинирано само едно поле от тип TextView:
- Although the use of a template xml file is not mandatory, this is the recommended way to build user interfaces for Android. You can see that the folder already contains a file – activity_main.xml, which contains the user interface template of the application you are creating. If you activate the template (by double-clicking on it), it will load into the graphical interface of the programing environment, thus allowing you to modify it by adding elements such as buttons, fields for output and input data and more. If you select the Text tab, you will be able to view the activity_main.xml file as text.
As you may have noticed, there is only one TextView field defined in this file:

- Това поле визуализира символния низ “Hello World”. Символният низ може да бъде променен директно тук чрез замяната на “Hello World”, но е по-добра практика да се дефинира нова променлива във файла strings.xml.
- menu: В тази папка се съдържа файла menu_main.xml, в който са дефинирани всички настройки за системното меню. При създаване на потребителско меню, то трябва да бъде дефинирано в отделен .xml файл в тази папка.
- mipmap: В тази папка се съдържат иконите за визуализиране на приложението в менюто на телефона. Виждате, че съществуват икони за всички възможни резолюции, които се поддържат от ОС Android. Ако решите да променяте или да направите нова икона на приложението си, то трябва да създадете съответните версии за всички налични резолюции. Ако това не се направи, програмната среда ще изведе грешка при компилиране на приложението.
- values: В тази папка се съдържат файлове в които е указана стойността за всички променливи или величини (например целочислена константа или символен низ). В папката вече се съхранява файла strings.xml. Ако активирате файла (с двойно натискане върху него), той ще се стартира в редактора на файлове. Можете да забележите, че във файла вече се съхраняват няколко символни низа, като единия от тях е наименуван app_name и има стойността, която зададохте при създаване на приложението.
5. Изпълнение на приложението в емулатор
- Преди да стартирате приложението в емулационната платформа, е необходимо да бъде настроено виртуалното устройство, с което ще се работи. За да се настрои устройството, отворете Tools -> AVD Manager
- This field displays the string “Hello World”. You can hardcode new text here, instead of “Hello World” or define and use a variable in the strings.xml file which is the better approach.
- menu: This folder contains the menu_main.xml file, which defines all the settings for the system menu. When creating a custom menu, it must be defined in a separate .xml file in this folder.
- mipmap: This folder contains the icons for the application in the phone menu. You can see that there are icons for all possible resolutions that are supported by the Android OS. If you decide to change or make a new icon for your application, you must create the appropriate versions for all available resolutions. If this is not done, the programming environment will display an error when compiling the application.
- values: This folder contains files that specify the value for all variables or quantities (for example, an integer constant or character string). The strings.xml file is already stored in the folder. If you activate the file (double-click on it), it will run in the file editor. You may notice that several character strings are already stored in the file, one of which is named app_name and has the value you specified when creating the application.
5. Execution of the application in an emulator
- Before running the application in the emulator, it is necessary to configure the virtual device which will be used. To set up this device, go to Tools -> AVD Manager

- След това изберете “Create virtual device”. Изберете “Phone” таба и маркирайте Nexus S. Натиснете Next.
- Then select “Create virtual device”. Select the Phone tab and highlight Nexus S. Select Next.

- От следващия екран, отворете “x86 Images”, изберете за версия на ОС => KitKat with API Level => 19 и Target => Android 4.4 (Google APIs). Изберете Next.
- From the screen, open “x86 Images”, select the OS version => KitKat with API Level => 19 and Target => Android 4.4 (Google APIs). Select Next

- Преименувайте устройството по ваш избор. В този случай е кръстено Nexus S API 19. Изберете Finish. Затворете AVD Manager.
- Rename the device as you wish. In this case it is called Nexus S API 19. Select Finish. Close AVD Manager.

- С по-горните стъпки създадохте своята първа виртуална машина, която работи с операционна система Android. След това свое действие вече разполагате с всички компоненти за изпълнението на своето първо приложение за ОС Android. За тази цел:
- Изберете от менюто Run – > Run ‘app’ (Кратки клавиши – Shift+F10). След компилиране на програмния код Android Studio ще стартира емулатора и ще визуализира приложението.
- Щом емулатора стартира и зареди операционната система приложението ви ще се стартира само. Можете да си взаимодействате с виртуалната машина използвайки мишката. Разгледайте функционалността на виртуалния смартфон.
Стартирането на емулатора може да отнеме няколко минути на по-слаби машини!
- With the above steps, you have created your first virtual machine that runs the Android operating system. After this action, you now have all the components to run your first Android application. For this purpose:
- Choose from the menu Run -> Run ‘app’ (Shortcuts – Shift + F10). After compiling the program code, Android Studio will start the emulator and display the application.
- Once the emulator starts and loads the operating system, your application will start automatically (Fig. 11). You can interact with the virtual machine using the mouse. Take a look at the functionality of the virtual smartphone.
The boot time of the virtual machine can take a couple of minutes on computers with low resources!

Вие създадохте и стартирахте своето първо приложение за Android!
You created your first Android application!
