Android: Programming for Developers
()
About this ebook
- Kick-start your Android programming career or just have fun publishing apps to the Google Play marketplace
- Explore the high-level Android asynchronous constructs available on the Android SDK
- Learn the internals of a game engine by building one
If you are an iOS developer or any other developer/programmer and you want to try your hands on developing applications on the Android platform, this course is for you. No prior programming experience is needed as this course will guide you right from the beginning to the advanced concepts of Android programming.
Read more from Raul Portales
Mastering Android Game Development Rating: 0 out of 5 stars0 ratingsAndroid Things Quick Start Guide: Build your own smart devices using the Android Things platform Rating: 0 out of 5 stars0 ratingsAndroid: Game Programming Rating: 0 out of 5 stars0 ratings
Related to Android
Related ebooks
Android Studio Development Essentials Rating: 5 out of 5 stars5/5Android Design Patterns and Best Practice Rating: 5 out of 5 stars5/5Mobile Application Development: JavaScript Frameworks Rating: 0 out of 5 stars0 ratingsXamarin Mobile Application Development for Android - Second Edition Rating: 0 out of 5 stars0 ratingsLearning Java by Building Android Games Rating: 0 out of 5 stars0 ratingsNode.js Web Development - Third Edition Rating: 2 out of 5 stars2/5Learning Android Application Development Rating: 0 out of 5 stars0 ratingsNode.js Design Patterns Rating: 4 out of 5 stars4/5Node Web Development, Second Edition Rating: 0 out of 5 stars0 ratingsJavaScript : Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsAndroid 4.4 App Development Essentials Rating: 4 out of 5 stars4/5Learning Dart Rating: 0 out of 5 stars0 ratingsHow To Program A Mobile Game Rating: 4 out of 5 stars4/5Mastering Dart Rating: 0 out of 5 stars0 ratingsAndroid System Programming Rating: 5 out of 5 stars5/5Android Programming for Beginners Rating: 3 out of 5 stars3/5Android Studio Cookbook Rating: 4 out of 5 stars4/5Asynchronous Android Rating: 4 out of 5 stars4/5Mastering Android Application Development Rating: 5 out of 5 stars5/5Learning Android Game Development Rating: 0 out of 5 stars0 ratingsInstant Java Password and Authentication Security Rating: 0 out of 5 stars0 ratingsAndroid NDK: Beginner's Guide - Second Edition Rating: 0 out of 5 stars0 ratingsProfessional Android Rating: 0 out of 5 stars0 ratingsAndroid Application Development Cookbook - Second Edition Rating: 5 out of 5 stars5/5Internet of Things Programming with JavaScript Rating: 0 out of 5 stars0 ratingsGradle for Android Rating: 0 out of 5 stars0 ratingsAndroid NDK Game Development Cookbook Rating: 0 out of 5 stars0 ratingsFlash Development for Android Cookbook Rating: 3 out of 5 stars3/5Android Programming For Beginners: The Simple Guide to Learning Android Programming Fast! Rating: 0 out of 5 stars0 ratingsSDL Game Development Rating: 0 out of 5 stars0 ratings
Programming For You
Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsSQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Unreal Engine from Zero to Proficiency (Foundations): Unreal Engine from Zero to Proficiency, #1 Rating: 3 out of 5 stars3/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsSpies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5
Reviews for Android
0 ratings0 reviews
Book preview
Android - Raul Portales
Table of Contents
Android: Programming for Developers
Android: Programming for Developers
Credits
Preface
What this learning path covers
What you need for this learning path
Windows
Mac OS X
Linux
Who this learning path is for
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Module 1
1. The First App
How Java and Android work together
The Android API
Java is object-oriented
What exactly is Android?
The development environment
A note to the existing developers who use Eclipse
The JDK
What if I already have Java?
Installing the JDK
Setting up Android Studio
What makes an Android app
Android resources
The structure of Android's Java code
Android packages
Our first Android app
Creating the project
A note on version controlling
Deploying and testing the app
Deploying to an emulator
Deploying to a real Android device
FAQ
Summary
2. Java – First Contact
Examining the log output
Exploring the project assets and code
Examining the layout file
Improving our app and deploying again
Modifying the UI
Meet Java
Java comments
Sending messages
Writing our first Java code
Writing our own Java methods
Examining the log output
FAQ
Summary
3. Exploring Android Studio
The Android Studio guided tour
Parts of the UI
The console
More console features
The project explorer
Transforming the editor into a design studio
E1 – the Preview toolbar
E2 – exploring the palette
E3 – the layout preview
E4 – the Component Tree
E5 – the Properties window
E6 – text and design view tabs
The project folder and file structure
FAQ
Summary
4. Designing Layouts
Exploring Android UI design
Structure of a UI design
Configuring and using widgets
Widget properties
Setting the size
Sizing using dp
Sizing fonts using sp
Determining size with wrap or match
Using padding and margin
Using the layout_weight property
Using gravity
More properties
Experimenting with widgets
Containing widgets in layouts
RelativeLayout
RelativeLayout in action
Using LinearLayout
Summary
5. Real-World Layouts
Building a real-world UI
Creating a tablet emulator
List-detail layout with ScrollView and LinearLayout
Designing a form with RelativeLayout
Summary
6. The Life and Times of an Android App
Introduction to the Android lifecycle
A simplified explanation of the Android lifecycle
Lifecycle phases – what we need to know
Lifecycle phases – what we need to do
The lifecycle demonstration app
Some other overridden methods
The structure of Java code – revisited
Summary
7. Coding in Java Part 1 – Variables, Decisions, and Loops
Java is everywhere
Syntax and jargon
More code comments
Storing and using data with variables
Types of variables
Primitive types
Reference types
Variable declaration
Variable initialization
Changing values in variables with operators
Expressing yourself demo app
Decisions
Indenting our code
More operators
If they come over the bridge, shoot them
Else do this instead
Switching to make decisions
The Switch Demo app
Repeating code with loops
While loops
Breaking out of a loop
Continue
Do while loops
For loops
Loops demo app
Summary
8. Coding in Java Part 2 – Methods
Methods revisited
The method structure
Modifiers
Return types
The name of a method
Parameters
Working in the method body
Using methods – demo apps
Real-world methods
Exploring method overloading
Scope and variables revisited
FAQ
Further reading
Summary
9. Object-Oriented Programming
Important memory management warning
Introducing OOP
What is OOP exactly?
Encapsulation
Polymorphism
Inheritance
Why do it like this?
A class recap
Taking a look at the code for a class
The class implementation
Declaring, initializing, and using an object of the class
The basic classes mini app
More things we can do with our first class
Remember that encapsulation thing?
Controlling class use with access modifiers
Class access in a nutshell
Controlling variable use with access modifiers
Variable access summary
Methods have access modifiers too
A method access summary
Accessing private variables with getters and setters
Setting up our objects with constructors
Static methods
Encapsulation and static methods mini app
OOP and inheritance
The inheritance mini app
Polymorphism
Abstract classes
Interfaces
FAQ
Summary
10. Everything's a Class
All Android UI elements are classes too
Reintroducing references
A quick break to throw out the trash
Stack and heap – a quick summary
So, how does this heap thing help me?
Using Button and TextView widgets from our layout
Inner and anonymous classes
FAQ
Summary
11. Widget Mania
Exploring Android UI objects
Declaring and initializing objects
Widget news flash
Exploring the palette
EditText
ImageView
Radio button and group
Anonymous classes
A switch widget
CheckBox
WebView
Date & Time
Android permissions and Marshmallows
Pre-Marshmallow permissions
Marshmallow permissions
The permission solution used in this book
The Widget exploration mini app
Setting up the widget exploration project and UI
Coding the widget exploration app
Summary
12. Having a Dialogue with the User
Dialog windows
The dialog demo mini project – introducing chaining
About the Note To Self app
Using naming conventions and String resources
How to get the Note To Self code
What we will do and when we will do it
What the user can do
Building the project and gathering resources
Downloading the images
Preparing the String resources
Coding the Note class
Implementing the dialog designs
Coding the dialog boxes
Coding the DialogNewNote class
Coding the DialogShowNote class
Showing our new dialogs
Adding a + icon to the action bar
Summary
13. Handling and Displaying Arrays of Data
A random diversion
Handling large amount of data with arrays
Arrays are objects
A simple array example mini app
Getting dynamic with arrays
A dynamic array example
Entering the nth dimension with arrays
A multidimensional array mini app
Array out of bounds exceptions
ArrayLists
The enhanced for loop
Arrays and ArrayLists are polymorphic
ListView and BaseAdapter
The problem with displaying lots of widgets
The solution
How to use ListView and BaseAdapter
Inner classes revisited
FAQ
Summary
14. Handling and Displaying Notes in Note To Self
Note To Self continued
Updating onCreate and preparing the UI
Creating a list item for ListView
Improvements in Note To Self
Persistence
Animation
Sound FX
Problems with the design of the code
FAQ
Summary
15. Android Intent and Persistence
Good Intents
Switching Activity
Passing data between activities
Adding a settings page to the Note To Self app
Creating SettingsActivity
Designing the Settings screen's layout
Enabling the user to switch to the Settings screen
Persisting data with SharedPreferences
Making the Note To Self app's settings persist
Coding the SettingsActivity class
Coding the MainActivity class
Specifying a parent Activity
More advanced persistence
What is JSON?
Java exceptions - try, catch, and finally
Backing up user data in Note To Self
FAQ
Summary
16. UI Animations
Animations in Android
Designing cool animations in XML
Fading in and out
Movement
Scaling or stretching
Controlling the duration
Rotating animations
Repeating animations
Combining animation properties with a set tag
Instantiating animations and controlling them with Java code
More animation features
Listeners
Animation interpolators
The Animations Demo app – introducing SeekBar
Laying out the animation demo
Coding the XML animations
Wiring up the Animations Demo app in Java
Adding animations to Note To Self
Defining the animations in XML
Controlling the animations in Java
FAQ
Summary
17. Sound FX and Supporting Different Versions of Android
Supporting multiple versions of Android
Detecting the current Android version
The SoundPool class
Building SoundPool the new way and the old way
Loading sound files into memory
Playing a sound
Stopping a sound
Introducing the Spinner widget
Making sound FX
Laying out Sound Demo UI
Coding the Sound Demo app
Sound FX touches to Note To Self
Deleting a note – introducing OnLongClick
FAQ
Summary
18. Design Patterns, Fragments, and the Real World
Introducing the model-view-controller pattern
The model
The view
The controller
The imperfections of Note To Self revisited
Android design guidelines
Real-world apps
The device detection mini app
Configuration qualifiers
Using configuration qualifiers – mini app
The configuration qualifier's summary
Fragments
Fragments have a lifecycle too
onCreate
onCreateView
onAttach and onDetach
onStart, onPause, and onStop
Managing Fragments with FragmentManager
Our first working Fragment mini app
Fragment reality check
FAQ
Summary
19. Using Multiple Fragments
Using singletons for the model layer
Inter-Fragment communications – interfaces revisited
The dual-Fragment address book mini app
Getting started
Alias resources
The NameAndAddress class
Creating the communication interface
Explaining the structure of the onListItemSelected method
Explaining the code that starts a new Activity
Explaining the code when the detail Fragment is already present
What do we need to do?
Creating the AddressDetailFragment class and layout
Coding PortraitDetailActivity and the layout
FAQ
Summary
20. Paging and Swiping
Building an image gallery/slider app
Implementing the layout
Coding the PagerAdapter class
Coding the MainActivity class
Running the gallery app
Building a Fragment pager/slider app
Coding the SimpleFragment class
fragment_layout
Coding the MainActivity class
The activity_main layout
Running the Fragment slider app
Summary
21. Navigation Drawer and Where It's Snap
Introducing the navigation drawer
The Where it's snap app
Preparing the resources
Placeholder code for three Fragments
Coding the MainActivity class and layout
Switching between Fragments
Setting up the drawer
Handling the back button
Summary
22. Capturing Images
Capturing images using the camera
The capturing images mini app
Adding the camera permission to the manifest
Defining a simple layout
Coding the MainActivity class
Running the Simple Photo app
Where it's snap – coding the capture Fragment
Creating the layout for the capture Fragment
Coding the capture Fragment
Testing the capture Fragment
Summary
23. Using SQLite Databases in Our Apps
Database 101
What is a database?
What is SQL?
What is SQLite?
The SQL syntax primer
The SQLite example code
Creating a table
Inserting data into the database
Retrieving data from the database
Updating the database structure
The Android SQLite API
SQLiteOpenHelper and SQLiteDatabase
Building and executing queries
Database cursors
The database mini app
Implementing the layout
Coding the database class
Coding MainActivity
Running the mini app
Summary
24. Adding a Database to Where It's Snap
The Photo class
Handling the SQLite database
Saving a new photo from the capture fragment
Displaying a photo from the database
Preparing the View layout
Coding the ViewFragment class
Coding the communications interface
Coding TitlesFragment
Coding TagsFragment
Coding the fragment communications in MainActivity
Running the app so far
Summary
25. Integrating Google Maps and GPS Locations
Global Positioning System
Where in the world – the GPS mini app
Where in the world – implementing a simple layout
Coding the Where in the world mini app
Running the Where in the world mini app
The Google Maps mini app
Preparing to connect to Google Maps
Acquiring an API key
Installing the Google Play services API
Coding the maps_activity layout
Coding MapsActivity
Running the Simple Map app
Summary
26. Upgrading SQLite – Adding Locations and Maps
Adding locations and maps to Where it's Snap
Updating the database
Adding member variables to represent location data
Updating the database version
Adding code in onUpgrade to upgrade the database for existing users
Updating the database creation code in onCreate for new users
Updating the addPhoto method to handle GPS coordinates
Updating the Photo class
Updating CaptureFragment
Updating ViewFragment
Adding location permissions
Testing the new map feature
Summary
27. Going Local – Hola!
The Localization mini app
Preparing the layout
Preparing the first strings.xml file
Making the app multilingual with the second strings.xml file
Adding a third language
Running the app
Localizing the Where it's snap app
Summary
28. Threads, Touches, Drawing, and a Simple Game
Threads
Problems with threads
Drawing with canvas and paint
The Android coordinate system
Android Canvas demo app
Handling touches
A simple game engine
Building a simple game of Pong
Adding sound files to the project
Coding the ball
Coding the paddle
Coding MainActivity
Coding SurfaceView
Coding the update method
Coding the draw method
Lock the screen orientation and make it full-screen
Running the game
Pong enhancements
Summary
29. Publishing Apps
Preparing to publish
Creating an app icon
Preparing the required resources
Building the publishable APK file
Publishing the app
Marketing
More to see
Summary
2. Module 2
1. Asynchronous Programming in Android
Android software stack
Dalvik runtime
ART runtime
Memory sharing and Zygote
Android process model
Process ranks
Process sandboxing
Android thread model
The main thread
The Application Not Responding (ANR) dialog
Maintaining responsiveness
Concurrency in Android
Correctness issues in concurrent programs
Liveness issues in concurrent programs
Thread coordination
Concurrent package constructs
Executor framework
Android primary building blocks
Activity concurrent issues
Manipulating the user interface
Service concurrent issues
Started services issues
Bound services issues
Service in a separate process
Broadcast receiver concurrent issues
Android concurrency constructs
Summary
2. Performing Work with Looper, Handler, and HandlerThread
Understanding Looper
Understanding Handler
Sending work to a Looper
Scheduling work with post
Using Handler to defer work
Leaking implicit references
Leaking explicit references
Updating the UI with Handler
Canceling a pending Runnable
Scheduling work with send
Cancelling pending messages
Composition versus inheritance
Multithreading with Handler and ThreadHandler
Looper message dispatching debugging
Sending messages versus posting runnables
Applications of Handler and HandlerThread
Summary
3. Exploring the AsyncTask
Introducing AsyncTask
Declaring AsyncTask types
Executing AsyncTasks
Providing indeterministic progress feedback
Providing deterministic progress feedback
Canceling an AsyncTask
AsyncTask Execution State
Handling exceptions
Controlling the level of concurrency
Common AsyncTask issues
Fragmentation issues
Memory leaks
Activity lifecycle issues
Handling lifecycle issues with early cancellation
Handling lifecycle issues with retained headless fragments
Applications of AsyncTask
Summary
4. Exploring the JobScheduler API
Introduction to JobScheduler
Setting running criteria
Scheduling a job
Implementing the JobService
Listing pending jobs
Canceling a job
Scheduling a periodic job
Applications of the JobScheduler
Summary
5. Interacting with the Network
Introducing Android HTTP clients
AndroidHttpClient
HttpURLConnection
Performing HTTP requests asynchronously
Retrieving a text response
Interacting with JSON web APIs
Converting Java objects to JSON
Interacting with XML web APIs
Converting Java objects to XML
Converting XML to Java objects
Customizing HTTP timeouts
Communicating securely over SSL sessions
Summary
6. Network Interactions with GCM
Introduction to GCM
Setting up and configuring GCM for your application
Registering the GCM Receiver
Setting up a registration service
InstanceID listener
Receiving downstream messages
Receiving messages from topic
Sending upstream messages
GcmListenerService delivery callbacks
Executing tasks with GCM Network Manager
Building a one shot task
Summary
7. Asynchronous Programing with RxJava
Introduction to RxJava
Cold versus Hot Observable
RxJava setup
Creating Observables
Transforming Observables
Understanding Schedulers
Performing IO operations with Schedulers
Canceling subscriptions
Composing Observables
Monitoring the event stream
Combining Observables
Observing UI Events with RxJava
Working with Subjects
Summary
3. Module 3
1. Setting Up the Project
The right tool for the right game
Do you want to use 3D?
Do you want to use physics?
Do you want to use Java?
Pros of building games with the Android SDK
Cons of building games with the Android SDK
I want the Android SDK!
The project – YASS (Yet Another Space Shooter)
Activities and Fragments
Project setup
Creating the stub project
Cleaning up
Choosing an orientation
Dealing with aspect ratios
Game architecture
GameEngine and GameObjects
Starting a game
Stopping a game
Managing game objects
UpdateThread
DrawThread
User input
Putting everything together
Moving forward with the example
Handling the back key
Honoring the lifecycle
Using as much screen as we can
Before Android 4.4 – almost fullscreen
Android 4.4 and beyond – immersive mode
Putting fullscreen together
Good practices for game developers
Object pools
Avoiding enhanced loop syntax in lists
Precreating objects
Accessing variables directly
Being careful with floating points
Performance myths – avoid interfaces
Summary
2. Managing User Input
The InputController base class
The Player object
Displaying a spaceship
Firing bullets
The Bullet game object
The most basic virtual keypad
Limitations and problems
Creating a virtual joystick
General considerations and improvements
Physical controllers
Handling MotionEvents
Handling KeyEvents
Detecting gamepads
Sensors and InputControllers
Selecting control modes
Summary
3. Into the Draw Thread
Using GameView
The GameView interface
StandardGameView
SurfaceGameView
Updating GameEngine
Updating the game layout
Improving DrawThread
Sprites
Updating the spaceship and bullets
Adding a frames-per-second (fps) counter
Spawning enemies – the GameController
Procedural/random
Deterministic/static
Hybrid approach
Our approach
The asteroids
More on the transformation matrix
Occlusion culling
Parallax backgrounds
Multiple backgrounds
Layers
Summary
4. Collision Detection
Detecting collisions
Who can collide?
Updating GameEngine
Handling collisions
Rectangular bodies
Adding visual feedback
Pros and cons
Circular bodies
Adding visual feedback
Pros and cons
Mixed collision detection
Adding visual feedback
Other options for shapes
Optimization
Spatial partitioning and QuadTree
Duplicated collisions
Summary
5. Particle Systems
General concepts
Particles
ParticleSystem
Initializers
Modifiers
Composite GameObjects and GameEngine
Making good particle systems
One shot
Asteroid explosions
Spaceship explosions
Emitters
Asteroid trails
The spaceship's engine
Summary
6. Menus and Dialogs
Custom fonts
Working with backgrounds
The power of XML drawables
State list drawables
State lists colors
Shape drawables
The GameFragment
Adding a score
Adding lives
Custom dialogs
BaseCustomDialog
Quit dialog
Pause dialog
Game Over dialog
Other dialogs
Designing for multiple screen sizes
Summary
7. To the Big Screen
Project configuration
Testing for Android TV
Declaring a TV Activity
Providing a home screen banner
Declaring it as a game
Declaring Leanback support
Declaring touchscreen capability as not required
Reviewing the manifest
Showing controller instructions
Dealing with overscan
Controller-based navigation
Dialogs and controllers
Beyond this book
Summary
A. Bibliography
Index
Android: Programming for Developers
Android: Programming for Developers
Develop your own responsive, reactive, and ready-to-deploy Android applications
A course in three modules
BIRMINGHAM - MUMBAI
Android: Programming for Developers
Copyright © 2016 Packt Publishing
All rights reserved. No part of this course may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this course to ensure the accuracy of the information presented. However, the information contained in this course is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this course.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this course by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Published on: August 2016
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78712-369-4
www.packtpub.com
Credits
Authors
John Horton
Helder Vasconcelos
Raul Portales
Reviewers
Nayanesh Ramchandra Gupte
Klaas Kabini
Márton Kodok
Paresh Mayani
Gavin Matthews
Sergio Viudes Carbonell
Antonio Hernández Niñirola
Content Development Editor
Rohit Kumar Singh
Graphics
Abhinash Sahu
Production Coordinator
Aparna Bhagat
Preface
Do you have a great idea for an app, but don't know how to make it a reality? Are you trying to start a career in programming, but haven't found the right way in? We will help you get to grips with Android programming concepts and develop your own applications. Whether you are Android beginner developer or an Android seasoned programmer, this course will explore how to achieve efficient and reliable multithreaded Android applications. We'll look at best asynchronous constructs and techniques, commonly used by Android Developer community, to execute computation intensive or blocking tasks off the main thread, keeping the UI responsive, telling the user how things are going, making sure we finish what we started, using those powerful multicore processors, and doing it all without wasting the battery. You will learn all the aspects of developing a game using a space shooter game as the example that will evolve with you throughout the chapters.
What this learning path covers
Module 1, Android Programming for Beginners, introduces you to the fundamental concepts of Android programming. At the completion of this module, you will be ready to start building your own custom applications in Android and Java
Module 2, Asynchronous Android Programming, will help you learn how to manage interactions between several threads and avoid concurrency and synchronization problems will help you build well-behaved applications with smooth, responsive user-interfaces that delight users with speedy results and data that's always fresh.
Module 3, Mastering Android Game Development, will guide you to build a real-time game from scratch using the Android SDK. Starting with the creation of a game engine and moving into handling user input, doing efficient drawing, implementing collision detection, playing sound effects, using animations, and so on.
What you need for this learning path
Android Studio running on any of the major operating systems can use the code in this course. Android Studio is a free software and full setup instructions for Windows are in the opening chapter. Android Studio is the recommended development tool, and at the time of publication, the minimum system requirements were as follows:
Windows
Microsoft® Windows® 8/7/Vista/2003 (32 or 64 bit)
2 GB RAM minimum; however, 4 GB RAM is recommended
400 MB hard disk space
At least 1 GB for Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Java Development Kit (JDK) 7
Optional for accelerated emulator: Intel® processor with support for Intel® VT-x, Intel® EM64T (Intel® 64), and Execute Disable (XD) Bit functionality
Mac OS X
Mac® OS X® 10.8.5 or a higher version, up to 10.9 (Mavericks)
2 GB RAM minimum; however, 4 GB RAM is recommended
400 MB hard disk space
At least 1 GB for the Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Java Runtime Environment (JRE) 6
Java Development Kit (JDK) 7
Optional for accelerated emulator: Intel® processor with support for Intel® VT-x, Intel® EM64T (Intel® 64), and Execute Disable (XD) Bit functionality
On a Mac OS, run Android Studio with Java Runtime Environment (JRE) 6 for optimized font rendering. You can then configure your project to use Java Development Kit (JDK) 6 or JDK 7.
Linux
A GNOME or KDE desktop
GNU C Library (glibc) 2.15 or later
2 GB RAM minimum; however, 4 GB RAM is recommended
400 MB hard disk space
At least 1 GB for the Android SDK, emulator system images, and caches
1280 x 800 minimum screen resolution
Oracle® Java Development Kit (JDK) 7
Tested on Ubuntu® 14.04, Trusty Tahr (64-bit distribution capable of running 32-bit applications).
For module 2, to follow along and experiment with the examples, you will need a development computer with a Java 7 (or 8) SE Development Kit and the Android Software Development Kit Version 9 or above (you will need at least Version 21 to try all of the examples).
You will also need Android Studio IDE. The examples have been developed using Google's new Android Studio IDE and use its integrated build system, Gradle. While you can run the examples using the emulator provided by the Android SDK, it is a poor substitute for the real thing. A physical Android device is a much faster and more pleasurable way to develop and test Android applications! Many of the examples will work on a device running any version of Android since 2.3, GingerBread. Some examples demonstrate newer APIs and as a result, require a more recent Android version—up to Android 5, Lollipop.
Specifically for module 3, you will need the latest version of Android Studio and the Android SDK for Lollipop or newer (API level 22) versions, which you can download using Android Studio.
Who this learning path is for
If you are an iOS developer or any other developer/programmer and you want to try your hands on developing applications on the Android platform, this course is for you. No prior programming experience is needed as this course will guide you right from the beginning to the advanced concepts of Android programming.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this course—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the course's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt course, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this course from your account at http://www.packtpub.com. If you purchased this course elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the course in the Search box.
Select the course for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this course from.
Click on Code Download.
You can also download the code files by clicking on the Code Files button on the course's webpage at the Packt Publishing website. This page can be accessed by entering the course's name in the Search box. Please note that you need to be logged in to your Packt account.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the course is also hosted on GitHub at https://github.com/PacktPublishing/Android-Programming-for-Developers. We also have other code bundles from our rich catalog of books, videos, and course available at https://github.com/PacktPublishing/. Check them out!
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our courses—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this course. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your course, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the course in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this course, you can contact us at <[email protected]>, and we will do our best to address the problem.
Part 1. Module 1
Android Programming for Beginners
Learn all the Java and Android skills you need to start making powerful mobile applications
Chapter 1. The First App
Welcome! In this chapter, we won't waste any time in getting started with developing Android apps.
We will look at what is so great about Android, what Android and Java are exactly, how they work and complement each other, and what this means to us as future developers.
After this, we will spend a little time setting up our development environment and then get straight to building and deploying our first app.
By the end of this chapter, we will have done the following:
Set up the Java Development Kit (JDK), part of the required Android development environment
Installed Android Studio, the final part of our Android development environment
Built our very first Android app
Deployed an Android emulator
Run our app on an Android emulator and a real device
How Java and Android work together
After we write a program in Java for Android, we click on a button to change our code into another form that is understood by Android. This other form is called Dalvik EXecutable (DEX) code, and the transformation process is called compiling. Compiling takes place on the development machine after we click on that button. We will see this work right after we set up our development environment.
Android is a fairly complex system, but you do not need to understand it in depth to be able to make amazing apps. The part of the Android system that executes (runs) our compiled DEX code is called the Dalvik Virtual Machine (DVM). The DVM itself is a piece of software written in another language that runs on a specially adapted version of the Linux operating system. So what the user sees of Android, is itself just an app running on another operating system.
The purpose of the DVM is to hide the complexity and diversity of the hardware and software that Android runs on but, at the same time, its purpose is to expose all of its useful features. This exposing of features generally works in two ways. The DVM itself must have access to the hardware, which it does, but this access must be programmer friendly and easy to use. The way the DVM allows us access is indeed easy to use because of the Android Application Programming Interface (API).
The Android API
The Android API is the code that makes it really easy to do exceptional things. A simple analogy could be drawn with a machine, perhaps a car. When you step on the accelerator, a whole bunch of things happen under the hood. We don't need to understand about combustion or fuel pumps because a smart engineer has provided an interface for us. In this case, a mechanical interface—the accelerator pedal.
Take the following line of Java code as an example; it will probably look a little intimidating if you are completely new to Android:
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
However, once you learn that this single line of code searches for the available satellites and then communicates with them in orbit around the Earth while retrieving your precise latitude and longitude on the planet, it is easy to begin to glimpse the power and depth of the Android API in conjunction with the DVM. Even if that code does look a little challenging at the moment, imagine talking to a satellite in some other way!
The Android API is mainly a whole bunch of Java code. So, how do we use all this code to do cool stuff without getting swamped by its complexity? How do we find and manipulate the pedals, steering wheel, and sunroof of the Android API?
Note
There are many different estimates to the number of lines of code that have gone into Android. Some estimates are as low as 1 million, some as high as 20 million. What might seem surprising is that, despite this vast amount of code, Android is known in programming circles for being lightweight
.
Java is object-oriented
Java is a programming language that has been around a lot longer than Android. It is an object-oriented language. This means that it uses the concept of reusable programming objects. If this sounds like technical jargon, another analogy will help. Java enables us and others (such as the Android development team) to write Java code that can be structured based on real-world things
and, here is the important part, it can be reused.
So, using the car analogy, we could ask the question: if a manufacturer makes more than one car in a day, do they redesign each and every part for each and every car?
The answer, of course, is no. They get highly skilled engineers to develop exactly the right components that are honed, refined, and improved over years. Then, that same component is reused again and again, as well as occasionally improved. Now, if you are going to be picky about my analogy, then you can argue that each of the car's components still have to be built from raw materials using real-life engineers, or robots, and so on.
This is true. What the software engineers actually do when they write their code is build a blueprint for an object. We then create an object from their blueprint using Java code and, once we have that object, we can configure it, use it, combine it with other objects, and more. Furthermore, we can design blueprints and make objects from them as well. The compiler then translates (manufactures) our custom-built creation into DEX code.
In Java, a blueprint is called a class. When a class is transformed into a real working thing, we call it an object.
Note
Objects in a nutshell
We could go on making analogies all day long. As far as we care at this point:
Java is a language that allows us to write code once that can be used over and over again.
This is very useful because it saves us time and allows us to use other people's code to perform tasks we might otherwise not have the time or knowledge to write for ourselves.
Most of the time, we do not even need to see this code or even know how it does its work!
One last analogy. We just need to know how to use that code, just as we only need to learn to drive the car.
So, a smart software engineer up at Google HQ writes a desperately complex Java program that can talk to satellites. He then considers how he can make this code useful to all the Android programmers out there. One of the things he does is he makes features such as getting the device's location in the world a simple one-line task. So the one line of code we saw previously sets many more lines of code in action that we don't see. This is an example of using somebody else's code to make our code infinitely simpler.
What exactly is Android?
We know that to get things done on Android, we write Java code of our own, which also uses the Java code of the Android API. This is then compiled into DEX code and run by the DVM, which in turn has connections to an underlying operating system called Linux.
Then the manufacturers of the Android devices and individual hardware components write advanced software called drivers, which ensure that their hardware (CPU, GPU, GPS receivers, and so on) can run on the underlying Linux operating system.
Our compiled Java code, along with some other resources, is placed in a bundle of files called an Android application package (APK), and this is what the DVM needs to run our app. This process is explained in the following figure:
In summary, all we need to do is learn how to read and code Java, so we can begin to learn and take advantage of the Android API.
All these tools are free, so let's take a look at the development environment we will be using.
The development environment
A development environment is a term that refers to having everything you need in order to develop, set up, and be ready to go in one place. We need the following two things to get started:
We talked a fair bit about compiling our Java code, as well as other people's Java code, into DEX code that will run on the DVM, on people's Android devices. In order to use Java code, we need a free software called the JDK. The JDK also includes other people's code, which is separate from the Android API.
There is a whole range of tools that are required to develop for Android, and we also need the Android API, of course. This whole suite of requirements is collectively known as the Android software development kit (SDK). Fortunately, downloading and installing a single application will give us these things all bundled together. This single application is called Android Studio.
Android Studio is an integrated development environment (IDE) that takes care of all the complexities of compiling our code and linking with the JDK and the Android API. Once we have installed the JDK and Android Studio, we can do everything we need inside this application.
Tip
What could possibly go wrong?
I got a lot of feedback via my website http://gamecodeschool.com about a previous book of mine that showed how to install an Android development environment. People said that setting this up can be the hardest part. So I've written this section to be as thorough as possible because not everybody has a smooth setup experience.
Hopefully, you won't need all the extra tips and detailed figures, but there are a few vagaries that can trip us up while setting up the development environment.
Most likely, these instructions will get you up and running quickly and cover all your issues. If there is an issue that I haven't managed to anticipate, don't let it beat you! I guarantee that you are not the first to have that exact issue. Perform a web search (use Google), be really specific in your search criteria, and I am confident you will be coding in no time at all.
This guide will get around 99% of the Windows user's setup in a couple of hours. All the coding and development information you need will be covered 100% step by step.
For Mac and Linux users, most of these instructions can be easily interpreted as the key points of the tutorial are more about what we do inside of the setup programs and less about the specific environment we are using. My apologies for not providing comprehensive instructions for every operating system.
A note to the existing developers who use Eclipse
There are multiple options regarding which software to use when developing Android apps. In the early days of developing Android, an IDE called Eclipse was most commonly used. A few years ago, a new official
contender for the best Android IDE was released. This was Android Studio. The problem after its first release was that it was still in the beta (not finished) stage. It had numerous bugs, including some quite awkward ones. However, even then it was the preferred IDE for many because of its smooth operation, cool looks, official status, and prestigious heritage.
Now that Android Studio has exceeded version 1, there is virtually no reason to use anything else, especially if you are just getting started with Android. If you already have Eclipse set up for Android development and really don't want to change, that's fine, the code in this book will work. However, there will be significant differences in the instructions, especially regarding the user interface (UI) designer. Also, the code in this book has been thoroughly tested by others and me in Android Studio.
The sections that follow will set up a development environment with the JDK and Android Studio as our IDE of choice.
The JDK
This can be as simple as downloading, double-clicking on the downloaded file, and following the installation instructions. However, sometimes it isn't. So, it is probably worth running through the installation process step by step and pointing out along the way a few options that can make things easier.
What if I already have Java?
Most PC/Mac computers already have Java installed. Many modern apps require Java, and a classic example of this is the game Minecraft. Java is subtly, but significantly, different from the JDK. Java on its own just runs programs that have been written in Java for PC. This is the PC equivalent to the DVM. Java on its own, however, will not compile our code or make other people's code that we need available. This more common version of Java is called the Java Runtime Environment (JRE). When we install the JDK, it will also install the JRE, whether you already have it or not. So, if you are conscientious about keeping your hard drive in order, you could uninstall the JRE using the Windows Control Panel in the usual way before proceeding. Then find and delete your existing Java folder.
This tutorial will then reinstall the latest version of the JRE as well as the JDK. If, however, you know that you have a program that uses Java and you don't want to mess with its configuration, then go ahead with this tutorial, but just be aware that there will be a JRE and an associated Java folder in two places on your hard drive.
To summarize the preceding in case anything is unclear: this tutorial assumes that you don't have an existing folder named Java, but will work just fine even if you do.
Installing the JDK
As a little bit of preparation before we install the JDK, you need to know which operating system you have and whether it is 32 or 64 bit. If you are unsure, use this little tip to find out.
Tip
Do I have a 32-bit or 64-bit Windows system?
To find out, right-click on My Computer (This PC on Windows 8) icon, left-click on the Properties option, and look under the System heading of the System type entry like this:
Now we are ready to install the JDK. This fairly simple set of steps will set up the JDK quickly. The only slight delay is the download itself, which could take a while on slower Internet connections. The actual installation process should be fast and trouble free:
Visit the Java JDK downloads page at http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html.
If the link has changed, conduct a web search for Java JDK download. The only potential stumbling block at this stage is that you click on a link for the JRE instead. JDK is what we need. The following is a screenshot of the important part of this page:
Your download page will most likely be slightly different. There will be a newer version of the JDK by the time you read these words, so the 8u51 will be different. That's OK, we just need whichever is the newest version. Simply click on the Accept License Agreement radio button that is highlighted in the previous screenshot and then click on the download link, which is on the right-hand side column corresponding to your operating system in the Product/File Description column. If you are not sure whether you have 32-bit or 64-bit Windows, refer to the tip before this section.
Wait while the JDK is downloaded to your hard drive.
In the folder where you've downloaded the JDK, right-click on the jdk-8u51-windows-x64.exe file and select Run as administrator. The precise name of the file you have will vary based on whether you have 32-bit or 64-bit Windows and what the current version of the JDK happens to be at the time.
There will be a series of windows that will guide us through the installation process. The most we have to do is just click on Next to proceed. As promised, I will guide you through them one at a time and point out when you might like to make changes or make a note of things. The following is a screenshot of the first window that you will see during the installation:
Now, click on Next and you will see this window:
On the window pictured in the previous screenshot, we can leave all the options at their default values. They are just what we need. The Install to setting is worth considering, however. By the time we install the JDK, Android Studio, and all the extra tools and files that come with it, we will have around 6 gigabytes of files and folders. Now, consider that we will also be making lots of projects throughout the course of this book. Ideally, we want all of these files, folders, and projects to be on the same hard drive. They don't have to be, but we might avoid some problems later on if they are. So, do you have at least 6 gigabytes of space on the hard drive that you've chosen by default? If not, you might like to browse to another folder. In addition to this, as we will see later on in this tutorial, it will be handy (but not essential) to simplify the folder names used to install the JDK. So, click on the Change button and you will see this window:
Browse to the hard drive where you will be installing all of your development tools. Then simplify the names of the folders in which you will install the JDK to just Java\JDK\. As you can see in the next screenshot, I have also switched to my D:\ drive, as I have more space there:
It actually doesn't matter what you call these folders as long as you remember where they are and what they are called, including whether they are uppercase or lowercase letters. Perhaps you can jot down a note or copy and paste them to a file on your desktop. When you are happy with the chosen installation location and folder names, go ahead and click on Next.
The next window will not appear on every installation. If you don't see the window pictured as follows, its fine, you can skip to step 13. If you do see the window, proceed to step 12.
Understandably, this window could cause confusion if you have never done any Java development before. You might be thinking that we had already chosen the destination folder for Java. We chose the location for the JDK. This window refers to the bog-standard Java—the JRE. This is what runs Java programs on your PC and, since we are developing for Android, we don't need it. However, we still need to choose a location in order to proceed. Accept the default and just click on Next. If you are a tidiness obsessive like me, you can change to the same Java folder from step 8 and then click on Next.
Next, you will see the window that says 3 Billion Devices Run Java. Android has over 1.1 billion devices alone at the time of writing this despite a slow start in 2015. You might also like to know that there are more than 18,000 different distinct devices. Seriously, Google it if you think it sounds crazy. You can do this while you wait for the installation to complete.
Now, you will see the final screen. Click on Next Steps if you are curious, but there is no need because we will be covering Android-specific next steps without delay.
Click on Close, and we are almost done installing the JDK, with just a few more precautionary steps left.
Now, we will make sure that Windows (and all its applications) know where to find the JDK. Right-click on your My Computer (This PC on Windows 8) icon and Properties | Advanced system settings | Environment Variables | New (under System variables and not under User variables). Now you can see the New System Variable dialog as follows:
As shown in the previous screenshot, type JAVA_HOME in Variable name and enter D:\Java\JDK in the Variable value field. If you've installed the JDK somewhere else, then the file path you enter in the Variable value field will need to point to where you've placed it. Be sure to type it correctly, make sure that the slashes \ are the right way around, and don't add any extra slashes.
Click on OK to save your new settings. Now, click on OK again to clear the Advanced system settings window.
We have successfully installed the JDK, which we need to develop Android apps with Android Studio, and we have also installed the JRE, if it wasn't installed already, which we won't be using, but this won't cause us any problems either.
Setting up Android Studio
Now that the JDK is installed and ready to go, we are only one step away from building our first Android app. Installing Android Studio can take a bit longer than the JDK and is a little more nuanced, but it is nothing a determined, aspiring, developer won't be able to handle with ease.
Tip
What could possibly go wrong?
This whole process could take an hour or two. Not because there is lots of work for us to do, but because we need to initiate some fairly large downloads. Also, at several different stages in the process, Android Studio will connect to the internet and update itself. If you have a fast internet connection, then you can probably knock a good percentage off of my rough estimate of the time required.
Now that we know what to expect, we can get on with the installation of Android Studio. Follow the given steps to do so. There is nothing especially tricky about this, and the few aspects that might need some consideration will be discussed as they arise:
Visit https://developer.android.com/sdk/index.html and click on the Download Android Studio for Windows button. If at the time of reading this the link has changed, simply Google Download Android Studio.
Next, you will see the Terms and Conditionspage as shown in the following screenshot:
Click on the I have read and agree with the above terms and conditions checkbox as highlighted in the previous screenshot.
Now, click on the DOWNLOAD ANDROID STUDIO FOR WINDOWS button. Wait for the download to complete.
Open the folder where you have downloaded Android Studio. Right-click on the android-studio-bundle-141.1980579-windows.exe file and select Run as administrator. Your file will most likely have a different name based on whichever is the current version of Android Studio at the time.
When you get the Do you want the following program to be allowed to make changes to this computer message, click on Yes. You will see the first window of the installation process.
Let's step through the setup process a window at a time. Pictured next is the first window that you will see when you start the setup process:
Click on Next. Now we can see a few options, as in this next screenshot:
Make sure that all the options have a tick next to them, and then click on Next.
The next window is the license agreement. Click on I Agree and you will see some settings that warrant a short discussion. Take a look at the next screenshot that shows you the Install Locationswindow:
In this step, we want to install the Android Studio IDE and Android SDK to the same hard drive where we installed the JDK. So you might just be able to click on Next at this point. However, if you've installed the JDK to another drive, then we need to change the drive and the folders we use at this step too. This isn't strictly essential, but it can avoid problems for some users.
For Android Studio Installation Location, choose the root of the drive where you've installed the JDK followed by \Android Studio. So in my case, this will be D:\Android Studio. For Android SDK Installation Location, choose the same hard drive and simply add Android\sdk as the location. So if, like me, you've installed the JDK on D:, then choose D:\Android\sdk. The next screenshot makes this clear:
Click on Next when you have selected your installation locations.
Next, you might see the Emulator Setup window as pictured in the next figure. If you do, then accept the default settings and click on Next; otherwise, you can skip to step 15. Don't worry if you don't see this screen, it is a minor issue to do with running the Android emulators a bit more smoothly. Most of the time, you will probably want to use a real device anyway.
We are nearly there now. The next window asks you to choose a start menu folder, just as when we install any new Windows app. You might want to make a note of this location. Click on Install to accept the default settings, and Android Studio will begin to install itself and extract the SDK to the appropriate folder that we selected earlier. This might take some time.
When you see the Installation Complete window, click on Next. Now, you will see the following window:
Click on Finish to bring up the second to last window of the installation process. Assuming that this is your first time using Android Studio, click on the I do not have a previous version of Android Studio or I do not want to import my settings radio button and click on OK.
Now, in the next figure, you get to choose the theme that Android Studio will use. If you like a conventional black text on white background appearance, then choose IntelliJ, and if you want a cool dark style, choose Darcula. You can alter any of these schemes from within Android Studio if you change your mind later.
Click on Next when you have chosen your theme.
Now Android Studio will connect to the Internet and download some of the Android tools that we will be using soon. Again, this could take a while.
When the Downloading Components window has done its work, it will present you with a Finish button. Click on it.
Finally, we are presented with the Welcome to Android Studio screen. This screen, among other things, allows us to start a new project or open an existing project. Take a look at the next screenshot:
You can close this window and take a break or leave it open and read on because we will be back here really soon.
This was a fairly lengthy tutorial but, hopefully, it wasn't too tough. Android Studio and the supporting tools that we need are installed and ready to go. We are really close now to building our first app.
First, let's look at the composition of an Android app a little.
What makes an Android app
We already know that we will write Java code that will itself use other people's Java code and will be compiled into DEX code that runs on the DVM. In addition to this, we will also be adding and editing other files as well. These files are known as Android resources.
Android resources
Our app will include resources such as images, sounds, and user interface layouts that are kept in separate files from the Java code. We will slowly introduce ourselves to them over the course of this book.
They will also include files that contain the textual content of our app. It is a convention to refer to the text in our app through separate files because it makes them easy to change, and this makes it easy to create apps that work for multiple different languages.
Furthermore, the actual UI layouts of our apps, despite the option to implement them with a visual designer, are actually read from text-based files by Android.
Android (or any computer), of course, cannot read and recognize text in the same way that a human can. Therefore, we must present our resources in a highly organized and predefined manner. To do so, we will use Extensible Markup Language (XML). XML is a huge topic but, fortunately, its whole purpose is to be both human and machine readable. We do not need to learn this language, we just need to observe (and then conform to) a few rules. Furthermore, most of the time when we interact with XML, we will do so through a neat visual editor provided by Android Studio. We can tell when we are dealing with an XML resource because the filename will end with the .xml extension.
You do not need to memorize this, as we will constantly be returning to this concept throughout the book.
The structure of Android's Java code
In addition to these resources, it is worth noting that Java, as used in Android, has a structure to its code. There are many millions of lines of code that we can take advantage of. This code will obviously need to be organized in a way that makes it easy to find and refer to. It is organized under predefined packages that are specific to Android.
Android packages
Whenever we create a new Android app, we will choose a unique name known as a package. We will see how to do this in the Our first Android app section. Packages are often separated into subpackages, so they can be grouped together with other similar packages. We can simply think of these as folders and subfolders.
We can also think of all the packages that the Android API makes available to us as books that contain code, from a library. Some common Android packages we will use include the following:
android.graphics
android.database
android.view.animation
As you can see, they are arranged and named to make what is contained in them as obvious as possible.
Tip
If you want to get an idea for the sheer depth and breadth of the Android API, then take a look at the Android package index at http://developer.android.com/reference/packages.html.
Earlier, we learned that reusable code blueprints that we can transform into objects are called classes. Classes are contained in these packages. We will see in our very first app how to easily import other people's packages along with specific classes from those packages for use in our projects. A class will almost always be contained in its own file, with the same name as the class, and have the .java file extension.
In Java, we further break up our classes into sections that perform the different actions for our class. We call these sections methods. These are, most often, the methods of the class that we will use to access the functionality provided within all those millions of lines of code. We do not need to read the code. We just need to know which class does what