Chapter 1
In This Chapter
Seeing reasons to develop Android apps
Starting with the basics of Android development
Working with the hardware
Getting familiar with the software
Google rocks! Google acquired the Android platform in 2005 (see the sidebar “The roots of Android,” later in this chapter) to ensure that a mobile operating system (OS) can be created and maintained in an open platform. Google continues to pump time and resources into the Android project. Though devices have been available only since October 2008, over a billion Android devices have now been activated, and more than a million more are being added daily. In only a few years, Android has already made a huge impact.
It has never been easier for Android developers to make money by developing apps. Android users trust Google, and because your app resides in the Google Play Store, many users will be willing to trust your app, too.
The real question is, “Why not develop for Android?” If you want your app to be available to millions of users worldwide or if you want to publish apps as soon as you finish writing and testing them or if you like developing on an open platform, you have your answer. But in case you’re still undecided, continue reading.
As a developer, you have an opportunity to develop apps for a booming market. The number of Android devices in use is greater than the number of devices on all other mobile operating systems combined. The Google Play Store puts your app directly and easily into a user’s hands. Users don’t have to search the Internet to find an app to install — they can simply go to the preinstalled Google Play Store on their devices and have access to all your apps. Because the Google Play Store comes preinstalled on most Android devices (see Chapter 19 for some exceptions), users typically search the Google Play Store for all their application needs. It isn’t unusual to see an app’s number of downloads soar in only a few days.
Because of all the application programming interfaces (APIs) packed into Android, you can easily develop full‐featured applications in a relatively short time frame. After you register as a developer at the Google Play Store, simply upload your apps and publish them. Unlike other mobile marketplaces, the Google Play Store has no app approval process. All you have to do is write apps and publish them.
The Android operating system is an open platform: Any hardware manufacturer or provider can make or sell Android devices. As you can imagine, the openness of Android has allowed it to gain market share quickly. Feel free to dig into the Android source code to see how it works, by visiting
. By using open source code, manufacturers can create custom user interfaces (UIs) and even add new features to certain devices.https://source.android.com
Android can run on devices of many different screen sizes and resolutions, including watches, phones, tablets, televisions, and more. Android comes supplied with tools to help you develop applications that support multiple types of devices. If your app requires a front‐facing camera, for example, only devices with front‐facing cameras can “see” your app in the Google Play Store — an arrangement known as feature detection. (For more information on publishing your apps to the Google Play Store, see Chapter 8.)
A mashup combines two or more services to create an application. You can create a mashup by using the camera and the Android location services, for example, to take a photo with the exact location displayed on the image. Or you can use the Map API with the Contacts list to show all contacts on a map. You can easily make apps by combining services or libraries in countless new and exciting ways. A few other types of mashups that can help your brain juices start pumping out ideas include the following:
https://developers.google.com/games/services/
for more information about Google Play Games services.Thank goodness you don’t have to be a member of Mensa to develop Android applications! Developing in Android is simple because its default language is Java. Though writing Android applications is fairly easy, writing code in general is no easy feat.
Although the Android operating system consists primarily of Java code, some of the framework isn’t written in Java. Android apps use small amounts of XML in addition to Java. You need to cement your basic understanding of XML before delving into this book.
If you already know how to use Java and XML, then congratulations — you’re ahead of the curve.
Android applications are written in Java — not the full‐blown version of Java that’s familiar to developers using Java Platform, Enterprise Edition (JEE), but a subset of the Java libraries that are most useful on Android. This smaller subset of Java excludes classes that aren’t suitable for mobile devices. If you have experience in Java, you should feel right at home developing apps in Android.
Even with a Java reference book on hand, you can always search at
or www.google.com
to find information about topics you don’t understand. Because Java isn’t a new language, you can find plenty of examples on the web that demonstrate how to do virtually anything.www.stackoverflow.com
An Android application can consist of one or more activities. An activity serves as a container for both the user interface and the code that runs it. You can think of activities as pages of your app — one page in your app corresponds to one activity. Activities are discussed in more detail in Chapters 3 and 5.
Every “page” in an Android application is a separate activity. In older versions of Android, you would place any element that you wanted to display onscreen directly into the Activity class. This arrangement works well when viewed on a phone’s small screen, on which you typically can’t see a lot of information at once. You may be able to see a list of tasks, or a task that you’re editing, but cramming both elements onto the screen at the same time is impossible.
On a tablet, however, you’re swimming in real estate. Not only does it make sense to let users see a list of tasks and edit them on the same page, but it also looks silly not to let them do so. The screen size on a tablet is simply too big to fill with a single long list of items or lots of empty space.
Android doesn’t allow you to easily put two activities on the screen at the same time. What to do? The answer is fragments.
Using fragments, a single list fragment can occupy half the screen, and an edit fragment can occupy the other half. Now each page of your app can contain multiple fragments. You can find out how to use fragments in your phone application in Chapter 9 and how to scale your app to tablets in Chapter 17.
Intents make up the core message system that runs Android. An intent is composed of two elements:
Intents are used to start activities and to communicate among various parts of the Android operating system. An application can send and receive intents.
When you send an intent, you send a message telling Android to make something happen. The intent can tell Android to start a new activity from within your application or to start another application.
Sending an intent doesn’t make something happen automatically. You have to register an intent filter that listens for the intent and then tells Android what to do — whether the task is starting a new activity or another app. If more than one receiver can accept a given intent, a chooser can be created to allow the user to decide which app to use to complete the activity — such as how the YouTube app allows the user to choose whether to watch videos in the YouTube app or in a browser.
Various registered receivers, such as the Gmail and the Hangouts apps, handle image‐sharing intents by default. When you find more than one possible intent filter, a chooser opens with a list of options to choose from and asks what to do: Use email, messaging, or another application, as shown in Figure 1-1.
Unlike the PC, where you manipulate the mouse to move the cursor, an Android device lets you use your fingers to do nearly anything you can do with a mouse. Rather than right‐click in Android, however, you long‐press an element until its context menu appears.
As a developer, you can create and manipulate context menus. You can allow users to use two fingers on an Android device, rather than a single mouse cursor, for example. Fingers come in all sizes, so design the user interface in your apps accordingly. Buttons should be large enough (and have sufficient spacing) so that even users with larger fingers can interact with your apps easily, whether they’re using your app on a phone or tablet.
A view, which is a basic element of the Android user interface, is a rectangular area of the screen that’s responsible for drawing and event handling. Views are a basic building block of Android user interfaces, much like paragraph <p> or anchor <a> tags are building blocks of an HTML page. Some common views you might use in an Android application might be a TextView, ImageView, Layout, and Button, but there are dozens more out there for you to explore. You can also implement your own custom views.
Many more views are ready for you to use. For complete details about views, check out the android.widget and android.view packages in the Android documentation at
.http://d.android.com/reference/android/widget/package‐summary.html
There are various ways to run multiple operations at the same time on Android without having to manage a thread yourself (which is generally not recommended). When loading data from a database to show on the screen, you’ll generally find yourself using loaders. Loaders take care of managing background threads for you, and they also watch your database for changes so that your UI updates when the data changes. You can find out more about loaders in Chapter 13.
For other kinds of background operations, you may find yourself using the AsyncTask class to run an operation on a background thread. AsyncTask(s) let you start a task to run in the background, and then they return the result to your foreground thread so that you can update your UI. This creates a clean programming model for asynchronous processing.
You use asynchronous processing for tasks that might take more than a small fraction of a second, such as network (Internet) communication; reading or writing to storage; or media processing. When users have to wait for your task to complete, use an asynchronous call and an element in the user interface to notify them that something is happening.
You may already know what a service is: It’s an application that runs in the background and doesn’t necessarily have a user interface. A classic example is an antivirus application that usually runs in the background as a service. Even though you don’t see it, you know that it’s running.
Android apps can also have background services. Most music players that can be downloaded from the Google Play Store, for example, run as background services. Users can then listen to music while checking email or performing other tasks that require the use of the screen.
It’s always so much fun to write apps for the latest and greatest devices! However, you may find yourself wanting to support older devices from time to time. After all, not all of your users may be running the very latest versions of Android.
Luckily, Android provides a solution. You can use the Android support library to make your apps compatible with devices all the way back to the Android Stone Age (circa 2010 A.D. or even earlier).
In addition to supplying fragments and loaders, the support library adds several other newer APIs to old devices, such as:
The action bar is where you’ll put many of the buttons and menus that will enable users to interact with your application. The action bar is almost always present across the top of the screen — and it’s therefore extremely difficult not to notice. See Figure 1-3 for an example of the action bar from the YouTube application.
Check out these elements on the action bar:
Up Button, app logo: Tap the Up button or the app logo on the action bar to move up one level.
Note the subtle distinction between the Up button and the Back button: Pressing the Back button returns the user to the previous activity, regardless of which app is being used; pressing the Up button returns the user to the previous activity in the current application, even if that activity wasn’t an activity the user was just performing.
Suppose that you’re viewing a web page in the Chrome browser and you tap a link to open the YouTube app. Pressing the Back button returns you to Chrome; pressing the Up button takes you to the YouTube app’s home page.
Visit
for more information about the versatility that this element of the user interface can add to your app.http://d.android.com/guide/topics/ui/actionbar.html
Users might want to access information from your app without explicitly starting it up first. For example, think about how the Gmail app allows users to preview emails in a notification before they open the Gmail app, or how you can see the current time on your launcher without having to open the clock app. These are examples of using notifications and launcher widgets.
Notifications: Android notifications are expandable and collapsible to allow users to see more information about them. For example, if your mother sends you a photo of her new puppy in a text message, you can see it directly in the notification without having to open the app. A notification about a new email message can show a preview of the message text so that it can be read directly.
In addition, a notification also lets the user take action on it directly from whichever app is being used. To reply to a birthday email from Grandma, for example, simply tap the Reply button on the notification to launch Gmail with an editor so that you can thank her.
Google gives developers the tools necessary to create top‐notch, full‐featured mobile apps. Google makes it simple to tap into, and make use of, all available hardware on a device.
To create a spectacular Android app, you should take advantage of all that the hardware has to offer. Don’t get us wrong — if you have an idea for an app that needs no hardware assistance, that’s okay, too.
Android devices come supplied with several hardware features that you can use to build apps. Table 1-1 describes the hardware features available on most Android devices.
Table 1‐1 Android Device Hardware
Android Hardware Feature |
What It Does |
Accelerometer |
Indicates whether the phone is moving |
Bluetooth radio |
Indicates whether a headset is connected |
Compass |
Indicates in which direction the user is heading |
Camera |
Take pictures and record video |
GPS receiver |
Indicates the user’s location |
Most Android devices are released with the hardware discussed in the following four sections, but not all devices are created equal. Android is free for hardware manufacturers to distribute, so it’s used in a wide range of devices, including some made by small manufacturers overseas (and it isn’t uncommon for some of these devices to be missing a feature or two).
Android devices come in all shapes and sizes: phones, tablets, ebook readers, watches, televisions, and cars. The engineers behind Android provide tools that let you easily deploy apps on multiple screen sizes and resolutions. Don’t worry — the Android team has done all the hard work for you. Chapter 4 covers the basics of screen sizes and densities.
The Android touchscreen opens a ton of possibilities to enhance users’ interaction with your apps. Users can swipe, flip, drag, or pinch to zoom, for example, by moving a finger on the touchscreen. You can even supply custom gestures in your app, which opens even more possibilities.
Android also supports multitouch capability, which lets a user touch the entire screen with more than one finger at a time.
Hardware buttons are old news. You can place buttons of any shape anywhere on the screen to create the user interface best suited for your app.
Combining the Android operating system with the GPS receiver on a device lets the developer access, and track, a user’s location at any time. The Foursquare social networking app is a good example — it uses the GPS feature to determine the user’s location and then accesses the web to determine the closest venues to the user.
Another helpful example is the Maps application’s ability to pinpoint a user’s location on a map and provide directions to that person’s destination. Combining Android with GPS hardware gives you access to the user’s exact GPS location. Many apps use this combination to show users where the nearest gas station, coffeehouse, or even restroom is located.
An accelerometer is a device that measures acceleration, and Android comes packed with accelerometer support. The accelerometer tells you whether a user’s device is being moved or shaken, and even in which direction it’s being turned. You can then use this information as a way to control your application.
You can use the accelerometer to perform simple tasks, such as determining when the device has been turned upside down and then completing an action. For example, you can immerse users in game play by having them shake their device to roll the dice. This level of usefulness is setting mobile devices apart from typical desktop personal computers.
Android gives you the tools you need to access (save and load) files on the device’s SD card — a portable storage medium that you can insert into compatible phones, tablets, and computers. To avoid bloating your app with extra required resources and hogging limited built‐in memory, you can download some or all of your application’s resources from your web host and save them to the device’s SD card (which makes users less likely to uninstall your app when they need to clear space on their devices).
Various Android tools are at your disposal while you’re writing Android applications. The following sections outline some of the most popular tools to use in your day‐to‐day Android development process.
Thanks to the Internet capabilities of Android devices, users can find real‐time information on the Internet, such as the next showing of a new movie or the next arrival of a commuter train. As a developer, you can have your apps use the Internet to access real‐time, up‐to‐date data, such as weather, news, and sports scores, or (like Pandora and YouTube) to store your application’s icons and graphics.
Including audio and video in your apps is a breeze in the Android operating system. Many standard audio and video formats are supported, and adding multimedia content to your apps — such as sound effects, instructional videos, background music, and streaming video and audio from the Internet — couldn’t be easier. Be as creative as you want to be. The sky’s the limit.
Your app can access a user’s Contacts list, which is stored on the device, to display the contact information in a new or different way, or you can create your own Contacts list. You might even write an app that couples the contact information with the GPS system to alert the user whenever she’s near a contact’s address.
Suppose that someone releases an app that sends a user’s entire Contacts list to a server for malicious purposes. For this reason, most functions that modify a user’s Android device or access its protected content need specific permissions. For example, if you want to download an image from the web, you need permission to use the Internet so that you can download the file to your device, and you need a separate permission to save the image file to an SD card. When your app is being installed, the user is notified of the permissions your app is requesting and can decide whether to proceed. Though asking for permission isn’t optional, it’s as easy as implementing a single line of code in your application’s manifest file. (Manifest files are described in Chapter 3.)
Users of the Android operating system aren’t limited to making calls, organizing contacts, or installing apps. As a developer, you have great power at your fingertips — you can even integrate maps into your application, for example, by using the Google Maps API.
Perhaps you want to write an app that displays a user’s current location to friends. You can spend hundreds of hours developing a mapping system, or you can use the Google Maps API. You can embed the API in your application without investing hundreds of development hours or even a single cent. Using the Maps API, you can find almost anything that has an address. The possibilities are endless — a friend’s location, the nearest grocery store, or your favorite gas station, for example.
Suppose that your application’s data is stored in the cloud (the Internet) and you download all of its assets the first time it runs. And then you realize that an image is outdated. To update the image, the app needs to know that the image has changed. You can use the Google Cloud Messaging framework to send a cloud‐to‐device notification (a message from the web server to the device) to direct the app to update the image. This process works even if your app isn’t running. When the device receives the message, it dispatches a message to start your app so that it can take the appropriate action.
44.220.184.63