- Как начать программировать под Android? Пошаговый план
- Изучаем язык
- Kotlin
- Изучаем Android SDK
- Изучаем популярные библиотеки
- Для многопоточного программирования
- Библиотеки для Dependency injection
- Библиотеки для сетевого взаимодействия
- Библиотеки для обработки изображений
- Библиотеки для работы с Json
- Библиотеки для хранения данных
- Learn Java for Android Development: Java Syntax
- Getting Started
- What You’ll Need
- Comments
- Variables
- Primitive Data Types
- Commonly Used Java Objects
- Class Permissions and Access
- Conditionals
Как начать программировать под Android? Пошаговый план
В этой статье мы рассмотрим, как начать программировать под Android. Пошаговый план с ссылками на ресурсы, курсы и книги и типичные вопросы, которые задают на собеседованиях на позицию junior Android-разработчика. Ну а если вы хотите быстро за 12 занятий вникнуть в азы Android — то приглашаю на практический онлайн-интенсив где вы с наставником разработаете собственный проект.
Итак, вы решили начать программировать под операционную систему Android. Для начала, вам нужно изучить язык программирования. В мире Android на момент написания статьи (март 2020) года используются как Java, так и Kotlin, однако второй официально рекомендован компанией Google и набирает всё большую популярность, так что, если вы не знаете ни одного языка программирования — то можете изучать Kotlin, если же вы уже знаете какой-либо объектно-ориентированный язык программирования, то изучить Java или Kotlin для вас не составит труда. На рынке тренд идет в сторону Kotlin.
Изучаем язык
Kotlin
Чтобы освоить Kotlin, вам могут пригодиться, следующие ресурсы:
- Try Kotlin — набор примеров и заданий по Kotlin cразу с консолью, в которой можно ввести код и проверить
- Kotlin Bootcamp for Programmers — туториал от Google
- Android Kotlin Fundamentals Course — набор мини-курсов для быстрого старта в Android — разработке
- Книга «Kotlin. Программирование для профессионалов» — Книга Джоша Скина и Дэвида Гринхола основана на популярном курсе Kotlin Essentials от Big Nerd Ranch. Яркие и полезные примеры, четкие объяснения ключевых концепций и основополагающих API не только знакомят с языком Kotlin, но и учат эффективно использовать его возможности
- Kotlin Bootcamp for Programmers — хороший видеокурс, объясняющий основы программирования на Kotlin
Чтобы освоить Java, вам могут пригодиться, следующие ресурсы:
- Изучаем Java Сьерра Кэти, Бэйтс Берт — эта книга не только научит вас теории языка Java и объектно-ориентированного программирования, она сделает вас программистом. В ее основу положен уникальный метод обучения на практике. В отличие от классических учебников информация дается не в текстовом, а в визуальном представлении.
- Become a Java Developer — курс от Udacity, который поможет вам изучить Java
- Джошуа Блох: Java. Эффективное программирование — эта книга является классикой для Java-программистов. Для новичков может быть несколько сложновата, но постарайтесь прочитать ее хотя бы половину и вернитесь к ней через годик, все сразу станет на свои места. Кстати, многие вопросы на собеседовании по Java взяты именно отсюда, так что не ленитесь, почитайте.
- Java. Библиотека профессионала. Том 1. Основы | Хорстманн Кей С. — Эта книга давно уже признана авторитетным, исчерпывающим руководством и практическим справочным пособием для опытных программистов, стремящихся писать на Java надежный код для реальных приложений. Быстро освоить основной синтаксис Java, опираясь на имеющийся опыт и знания в программировании.
Изучаем Android SDK
Как только вы освоили базовый синтаксис и поняли базовые концепции, переходите к изучению Android SDK, параллельно читая перечисленные выше книги. Изучение Android SDK вы можете начать с таких ресурсов как:
- Android Kotlin Fundamentals — набор туториалов для начинающих Android-разработчиков от Google на языке программирования Kotlin. Из курса вы узнаете об основных компонентах Android SDK, таких как Activity, Intent, BroadcastReceiver и других.
- Become an Android Developer — курс на Udacity, где за 6 месяцев вам расскажут от том как разрабатывать мобильные приложения под Android
- Школа мобильной разработки — набор лекций об устройстве Android от Яндекс. Часть материала немного устарела, но даже сейчас будет очень полезна как начинающим, так и уже более-менее опытным разработчикам.
- Android Programming: The Big Nerd Ranch Guide — достаточно понятная книга для новичков, чтобы понять программирование под Android OS
- The Busy Coder’s Guide to Android Development — книга, которая уже, наверное стала классикой для Android — программистов, один из самых полных источников знаний по Android OS
Это далеко не полный список, материалов огромное количество, но изучив вышеперечисленные ресурсы, вам с запасом хватит знаний для программирования под Android. Главное — не забывайте ежедневно практиковаться, общаться с наставником или ментором чтобы быстрее понимать свои ошибки и учиться на них.
Изучаем популярные библиотеки
Итак, вы неплохо знаете синтаксис языка, понимаете ООП, умеете применять наследование там где оно нужно и ваши приложения более-менее работают. Возможно, еще без применения архитектуры (MVP/MVVM/VIPER/RIBs) и без навороченных библиотек или фрэймворков. Самое время изучить и их.
В этом разделе я приведу список наиболее популярных библиотек, который используются в большинстве Android — проектов. Изучив их, вы смело сможете претендовать на звание junior или даже middle — разработчика.
Для многопоточного программирования
- RxJava 2 — видеокурс введение в RxJava на Stepic или бесплатный базовый курс по RxJava
- Kotlin Coroutines — набор туториалов и документация по корутинам от Jet Brains
- Основы работы с WorkManager— туториал по работе с WorkManager
- Advanced Coroutines with Kotlin Flow and LiveData — туториал от Google как рабоать с корутинами и LiveData
Библиотеки для Dependency injection
Библиотеки для сетевого взаимодействия
- Retrofit — пошаговый туториал, где вы создадите приложение для поиска фильмов
Библиотеки для обработки изображений
Библиотеки для работы с Json
Библиотеки для хранения данных
- Room — мини-курс, который поможет понять основы Room + LiveData
- Realm
Изучив, материалы из этого списка вы уверенно сможете претендовать на роль джуниор-разработчика, а в следующем посте мы рассмотрим наиболее часто задаваемые вопросы на собеседованиях. А прямо сейчас приглашаю вас на онлайн-интенсив по разработке
Источник
Learn Java for Android Development: Java Syntax
In this tutorial series, you’ll become familiar with Java, the programming language used to develop Android applications. Our goal is to prepare those already familiar with one programming language, such as PHP or Objective-C, to become comfortable working with the Java programming language and dive into Android app development. In this specific tutorial, you’ll learn the basics of Java syntax, including how to create comments, define variables, craft conditional statements and iterate using loops. If you’re new to Java, or just looking to brush up on the details, then this is the tutorial series for you!
Getting Started
As far as prerequisites go, we’re not going to make many assumptions about your programming experience. We are going to assume you understand how to program (perhaps in PHP, or Visual Basic or C++), but that you are unfamiliar with the specifics of programming in the Java language. We’re not going to go into the details of why you would want to do a for-loop versus a while-loop, but we will show you, in Java, the syntax of both types of loops. Said another way, we aren’t going to teach you to program; we’re going to provide you with clear examples of commonly used Java language constructs and principles, while pointing out some Android-specific tips and tricks.
What You’ll Need
Technically, you don’t need any tools to complete this tutorial but you will certainly need them to develop Android applications.
To develop Android applications (or any Java applications, for that matter), you need a development environment to write and build applications. Eclipse is a very popular development environment (IDE) for Java and the preferred IDE for Android development. It’s freely available for Windows, Mac, and Linux operating systems.
For complete instructions on how to install Eclipse (including which versions are supported) and the Android SDK, see the Android developer website.
Now let’s look at some more helpful Java syntax.
Comments
Most programming languages allow for comments and Java is no different. You can encapsulate any number of lines of text by beginning your comment with /* and ending your comment with */. For example:
You can also provide comments after code on a single using //. For example:
Java also has a standard type of comments called Javadoc that can be used to not only comment code, but also easily create code documentation. This topic is rather large on it’s own, but here’s an example of what Javadoc comments looks like:
Variables
A variable is simply a piece of data. Java variables generally fall into two categories:
- Primitive data types, like int, float, double, char, etc.
- Java objects (as defined by a class definition)
Variables are used for different purposes. Sometimes variables are used to store values that can change, or be modified, over time. For example, a variable called counter might be incremented on occasion. Other variables, notably class variables that remain the same for all instances of a given class, should be defined using the static keyword. Other times variables might represent constants—these variables should use the keyword final to show they do not change over time.
A variable is only valid within its territory, or scope. Variable scope is often controlled by curly braces < >. When a variable is defined, it is valid within those braces. If you try to access a variable outside of the braces, it will be undefined. Class member variables in object-oriented languages are often called attributes. They can also be called fields or properties.
Like other common programming languages, you’ve got your assignment operator, the equals sign:
You’ve also got your arithmetic operators like +, -, *, /. Remember to use parenthesis to force the order of operations as necessary:
Finally, you have your typical unary operators, which allow you to modify a single variable with a simple statement:
Note that the increment (++) and decrement (—) operators can be prefix or postfix, meaning that the increment can be executed before or after any conditionals are determined, if the item is used in a loop. Generally, we like to stick to postfix statements, so code is more readable.
Primitive Data Types
Let’s look at some of the primitive data types available in the Java programming language:
- byte
- A byte variable is an 8-bit signed integer between -128 and 127. Often used for arrays.
- short
- A short variable is a 16-bit signed integer between -32,768 and 32,767. Again, often used for arrays.
- int
- An int variable is a 32-bit signed integer between -2,147,483,648 and 2,147,483,647. This is the most commonly used “number” variable.
- long
- A long variable is a 64-bit signed integer between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. Used when the int data type isn’t big enough.
- float
- A float variable is a single precision 32-bit floating point number.
- double
- A double variable is a double-precision 64-bit floating point number. Use this data type for decimal values.
- boolean
- A boolean variable has only two possible values: true and false. Use this data type for conditional statements.
- char
- A char variable is a single 16-bit Unicode character.
Primitive types variables can be defined by specifying the datatype, followed by the variable name, then an equals sign and an initial value. All Java statements end with an semicolon. For example, the following Java statement defines a variable called iVal, with an initial value of 1:
Like many other languages, you can define a zero-based array of a specific data type. For example, the following defines an array of three integer values (first four powers of 2):
Commonly Used Java Objects
The Java libraries provide a number of helpful objects for use with common data structures. All objects are derived from the Object class. There are class counterparts for all primitive data types. For example, the Integer class encapsulates an int value and provides a number of helpful methods for manipulating integer data values. For example, the following Java code instantiates a integer variable called iVal, then creates an Integer object using a constructor that takes an integer, and then uses an handle method available in the Integer class to extract a float variable equivalent.
Perhaps the most common object you’ll use in Android applications is the String. The String class is used to encapsulate human-readable text characters, which are often displayed to the screen. If you are modifying or building strings up from smaller parts, you’ll also want to check out the StringBuffer and StringBuilder classes.
For a list of common Java data types, the Android reference includes documentation for the java.lang package. You can also find the common input/output objects in the java.io package.
For more complex data structures like lists, queues, stacks, dates, and times, appropriate classes are in the java.util package.
Finally, Android applications rely on a number of helpful classes that define the commonly used application components, like Activity, Application, Dialog, and Service. These classes can be found in the android.app package.
Class Permissions and Access
You can control the visibility of a class as well as its variables and methods by specifying an item’s access level. The access levels are: public, protected and private. Generally speaking, if you want something to be accessible from outside a class, use public. If a method or variable should only be accessible from the class itself, use private. Use protected when the class or any of its subclasses need access.
For example, the following SillySensor class definition defines several variables and methods with different access levels:
- A class variable called sensorData, which is only visible within the class
- A public constructor that can be called outside the class
- A private method called calibrate(), which can only be called from within the class itself
- A protected method called seedCalibration(), which can be called from within the class itself, or by a subclass
- A public method called getSensorData(), which can be called from anywhere, allowing for “read-only” access to the sensorData variable
Conditionals
Java includes conditional statements, which can be used to execute snippets of code if, and only if, certain conditions are met. Typically, a conditional statement involves two sides. If the two sides are equivalent, the statement is true, otherwise it is false.
Java has all the typical conditional operators, such as:
- == equal to, as in (a == b)
- != not equal to, as in (x != y)
- > greater than, as in (z > y)
- >= greater than or equal to, as in (q >= z)
- less than, as in (b less than or equal to, as in (a >,
Источник