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 обычно предпочтительней, поскольку отделяет программной логику от определения макетов и позволяет легче определять разные ресурсы макетов, для разных устройств. Можно также смешивать оба подхода.
Источник
Android Developer
Step by step guide to becoming an Android developer in 2021
The intent of this guide is to give you an idea about the Android development landscape and to help guide your learning if you are confused. Before we start, please note that the roadmap is opinionated, and you might have different opinions than those of the author. Having said that, we would love to hear your opinions and incorporate them in the roadmap if suitable.
There are multiple ways to develop applications for the android; you can go down the path of hybrid application development where flutter, react-native, or NativeScript are the most common contenders. Flutter uses Dart, whereas React Native and Native Script rely on JavaScript. Answering the question of hybrid vs native is out of the scope of this roadmap. This roadmap is focused on the native Android apps development but if you are interested in learning any hybrid framework, my personal preference is react-native and I would recommend you to checkout the Frontend Developer Roadmap.
Here is the full version of the roadmap in a single image and after that we have the broken down version with the resources and links to learn more about each of the boxes.
Broken Down Version
Below is the broken down version of the roadmap with links and resources to learn more about each of the items listed in the complete roadmap above.
Pick a Language
For the languages, you can develop android apps either by using Kotlin or Java.
Although, you can use both Kotlin and Java to develop native android apps, Google announced in 2019 to make Kotlin the preferred way of developing android applications. If you were to start learning android development today, Kotlin should be your language of choice.
Install the Android Studio and learn the basics of Kotlin to get started.
We have also listed down some free resources which you can use for the items listed in the image above. If you have some better ones, please do suggest. Also, you don’t need to go through all of them, just go through them and pick what you like.
Version Control Systems
Version control systems record your changes to the codebase and allow you to recall specific versions later. There are multiple Version Control Systems available but Git is the most common one these days.
Here are some of the resources to get you started. Feel free to google and find something else that you find easier.
Building an Application
Here is the list of items that you are going to need when developing Android applications. Please note that, this is an exhaustive list, and you don’t need to know it all from the get-go. Get an idea of the items listed, and just start building some apps and keep the items listed in the back of your mind and have a deep dive when using them.
To learn more about the items listed in the image above, here are the links to the relevant docs
I would highly recommend watching this free course from google on Developing Android Apps with Kotlin. Also, here are some of the resources to learn more about the topics listed above.
That wraps it up for the android developer roadmap. Again, remember to not be exhausted by the list; just learn the basics and start working on some project, rest of the learnings will come along the way. Good luck!
For any suggestions, improvements and feedback, feel free to submit an issue or reach out to me on twitter @kamranahmedse.
Open Source
The project is OpenSource, 7th most starred project on GitHub and is visited by hundreds of thousands of developers every month.
A considerable amount of my time is spent doing unpaid community work on things that I hope will help humanity in some way. Your sponsorship helps me continue to produce more open-source and free educational material consumed by hundreds of thousands of developers every month.
Stay Informed
Subscribe yourself to get updates, new guides, videos and roadmaps in your inbox.
Free subscription for updates
Support the project by paying as little as 5$ per month
Источник
Android Design Guidelines
When learning Android app development, one of the most important topics to understand is how to create delightful mobile interfaces and interactions. This means understanding the conventions within the Android universe, common style guidelines, patterns, etc.
The official Android docs has an excellent set of design resources. This section will highlight a few key design guidelines and link to the appropriate guides. You can also check out these Android design tips for a quick overview.
Check out these design principles which were developed by and for the Android User Experience Team to keep users’ best interests in mind. Consider them as you apply your own creativity and design thinking. Deviate with purpose.
With the release of Android 5.0, there are updated guidelines for modern Android UI design. These guidelines are called «material design». This new framework encompasses several changes to the interface of Android apps and Google strongly encourages the adoption of these new principles. Check the following resources below for details:
- Material Design Docs — Overview of material design
- Material Design for Developers — Developer guides for material
- Material Design Examples — Blog posting beautiful material designs
- Material Palette — Easy material color selection
- Material Design Guidelines — Principles that guide material design
Using these materials, you can understand and begin adhering to these guidelines for your own applications.
As you plan your app for Android, keep in mind that different platforms play by different rules and conventions. Design decisions that make perfect sense on one platform will look and feel misplaced in the context of a different platform. If you have built web and/or mobile apps in the past, review this Pure Android Guide for look at how to avoid making Android design faux pas. Check this article from jackrabbit for a more detailed breakdown.
Check out the UI Overview page which provides a high-level tour of key UI element. In particular, check out the Common App UI which outlines the key UI elements including the Action Bar, Navigation Drawer and Content Area.
Check out the color scheme guide and the android colors which includes common color palettes for Android apps. For nice color schemes check out:
- Material Palette and Material Colors
- Coolors generator — Handy color scheme generator
- ColourLovers for color scheme
- adobe kuler color wheel for color selection
- Colors library — Android library with pre-defined colors
For material design, check out the Material Palette for color selection.
Check out the typography guide to understand the common font types for Android apps and default type colors and sizes. See the calligraphy library for each custom fonts.
An icon is any graphic that takes up a small portion of screen real estate and provides a quick, intuitive representation of an action, a status, or an app. Icons must be created to work across a wide array of devices. There are also many different types of icons such as the «Launcher» icon on the home screen, ActionBar icons, and notification icons. To get started with icons, check out the material icons style guide. If you are looking for actual icons to use, check out materialdesignicons.com and material.io icons.
Check out the iconography guide and icon design guidelines for a detailed look. In particular, work to understand the design tips and follow the correct naming conventions for different icons.
Android powers millions of phones, tablets, and other devices in a wide variety of screen sizes and form factors. By taking advantage of Android’s flexible layout system, you can create apps that gracefully scale from large tablets to smaller phones. Check out the following resources for more information:
There are about a dozen common UI patterns that are integrated into almost every app. When you are building Android screens, it’s essential you adhere to these common pattern guides. The most important ones are listed below:
- Overall App Structure — High-level guidelines for the elements of an app.
- Gestures UX — Gestures allow users to interact with your app by manipulating the screen objects you provide.
- Navigation UX — Consistent navigation is an essential component of the overall user experience
- ActionBar UI — The action bar is one of the most important design elements you can implement
- Swiping Views — Efficient navigation is one of the cornerstones of a well-designed app.
- Navigation Drawer — The navigation drawer is a panel that transitions in from the left edge of the screen and displays the app’s main navigation options.
- Notifications UI — Allows your app to keep the user informed about events, such as new chat messages or a calendar event.
- Settings — Place in your app where users indicate their preferences for how your app should behave
Following these and related guides explains in detail how to create consistent and delightful mobile apps.
One of the best ways to understand the best practices and patterns for app design is benchmarking other popular applications on the platform. One of the best ways to do this is to buy an Android device and use a variety of popular applications. In addition to that, we can benchmark by checking websites dedicated to giving us a wide sampling of apps and how they achieve certain common UI patterns. For this, we can check out the following sites:
- UI-Oh-My — Great resource for seeing screenshots of apps.
- inspired-ui — Endless list of beautiful UI design
- mobilepatterns — Common screen patterns neatly organized
- pttrns — List of android screens in categories
- androidniceties — Blog of beautiful interfaces
- androidux — Explores common patterns for UX
- androidpatterns — UI patterns organized by questions, such as «How can I let users manage their accounts?»
Using these sites above to build up an intuitive understanding of how to build different UIs in your apps.
When developing a mobile application, there are a few stages you will probably go through during an agile development method. First, you decide on the core value of the app and determine the key user scenarios. From there, it is helpful to begin identifying and sketching the different distinct user interfaces and user interactions for the app.
The simplest way you can wireframe is by creating low-fidelity sketches on paper by hand. You can print a scaled Android frame to make this easier. You can also leverage many excellent digital tools as well:
- Pencil Project — Excellent free cross-platform wireframing tool with Android stencils
- FluidUI — Online wireframing tool, free for limited use with comprehensive android stencils
- MockingBird — Online wireframing tool, free for limited use, no android stencils
- Balsamiq — Extremely powerful wireframing tool used by many industry professionals
See the android docs on wireframing for additional perspective and examples.
Источник