Medium 9781449319236

Learning Android: Develop Mobile Apps Using Java and Eclipse

Views: 733
Ratings: (0)

Want to build apps for Android devices? This book is the perfect way to master the fundamentals. Written by experts who have taught this mobile platform to hundreds of developers in large organizations and startups alike, this gentle introduction shows experienced object-oriented programmers how to use Android’s basic building blocks to create user interfaces, store data, connect to the network, and more.

Throughout the book, you’ll build a Twitter-like application, adding new features with each chapter. You’ll also create your own toolbox of code patterns to help you program any type of Android application with ease.

  • Become familiar with the Android platform and how it fits into the mobile ecosystem
  • Dive into the Android stack, including its application framework and the APK application package
  • Learn Android’s building blocks: Activities, Intents, Services, Content Providers, and Broadcast Receivers
  • Create basic Android user interfaces and organize UI elements in Views and Layouts
  • Build a service that uses a background process to update data in your application

List price: $27.99

Your Price: $22.39

You Save: 20%

 

16 Slices

Format Buy Remix

1. Android Overview

ePub

In this chapter, you will learn how Android came about. We’ll take a look at its history to help us understand its future. As this mobile environment enters a make-or-break year, we look at the key players in this ecosystem, what motivates them, and what strengths and weaknesses they bring to the table.

By the end of this chapter, you will better understand the ecosystem from a business point of view, which should help clarify the technology choices and how they relate to long-term advantages for various platforms.

Android is a comprehensive open source platform designed for mobile devices. It is championed by Google and owned by Open Handset Alliance. The goal of the alliance is to “accelerate innovation in mobile and offer consumers a richer, less expensive, and better mobile experience.” Android is the vehicle to do so.

As such, Android is revolutionizing the mobile space. For the first time, it is a truly open platform that separates the hardware from the software that runs on it. This allows for a much larger number of devices to run the same applications and creates a much richer ecosystem for developers and consumers.

 

2. Java Review

ePub

The purpose of this chapter is to do a quick review of Java syntax and concepts. This is not in any way a true in-depth introduction to Java (for that we suggest Oracle’s Java Tutorial). Rather, the intention is to provide a quick run-through from the very basics to more complex concepts that you will definitely need to be comfortable with in order to program for the Android platform. It is assumed that you have installed the Java Development Kit (JDK) 1.6 on the development machine (see Chapter 4 to install the JDK).

As with all opening examples for most languages, let us first cover the basic Java program and its execution with the classic “Hello World” example:

At this stage we are looking at a really basic program that does not get into any of Java’s syntax and utility. It does contain within it the three main elements of Java: a class, a variable, and a method. A variable can be considered a noun, and a method can be considered a verb. Both are parts of a class. The method that is contained is the line public static void main(String[] args). This main method is what the Java runtime system calls (it’s an entry point, so to speak). Without this method in the class that is specified to the Java interpreter, an error occurs and the program terminates. Now onto the simple example, SimpleExample.java:

 

3. The Stack

ePub

This chapter offers a 9,000-foot overview of the Android platform. Although you’re concerned primarily with writing Android applications, understanding the layout of the system will help you understand what you can or cannot easily do with Android.

By the end of this chapter, you’ll understand how the whole system works, at least from a high level. You should be able to identify each of the main layers of the platform and have a general understanding of its purpose.

The Android operating system is like a cake consisting of various layers. Each layer has its own characteristics and purpose—but the layers are not always cleanly separated and often seep into one another.

As you read through this chapter, keep in mind that we are concerned only with the big picture of the entire system and will get into the nitty-gritty details later on. Figure 3-1 shows the parts of the Android stack.

Android is built on top of the Linux kernel. Linux is a great operating system, and is the poster child of open source. Its kernel has been hardened and tightened over the years by many engineers continually improving it. Many users depend on Linux every day (often unknowingly).

 

4. Installing and Beginning Use of Android Tools

ePub

In this chapter, you will learn how to set up your environment for Android development. We’ll go beyond just listing where you can download the software, and will cover some of the best practices in getting set up. We’ll look at choices for development operating systems as well as the Android tools available. You will see the good, the bad, and the ugly of the various tool and platform choices that you’re about to make (or that someone else has already made for you).

By the end of this chapter, you will have your entire development environment set up. You’ll be able to write a Hello World application, build it, and run it on the emulator (or a physical device, if you want).

We use ~ to refer to your home directory. On Mac OS X, that’s typically something like /Users/marko. On Linux, it would be /home/marko, on Windows Vista and 7, it would be C:\Users\marko, and on Windows XP it would be C:\Documents and Settings\marko. To keep things simple and consistent, we’re going to use Unix-style forward slashes and not Windows backslashes to denote file path separators.

 

5. Main Building Blocks

ePub

In this chapter, you will learn Android’s capabilities by looking at the big features it offers. We’ll give you a high-level overview of what activities are, how intents work, when and how to use services, how to use broadcast receivers and content providers to make your app scale, and much more.

By “main building blocks,” we refer to the pieces of an application that Android offers you to put together into an Android app. When you start thinking about your application, it is good to take a top-down approach. For instance, most programmers design applications in terms of screens, features, and the interactions between them. You start with a conceptual drawing, something that you can represent in terms of “lines and circles.” This approach to application development helps you see the big picture—how the components fit together and how it all makes sense.

By the end of this chapter, you will understand the main Android components for building applications. You should conceptually know when you’d use what component. You will also see how these components relate to a real-world application.

 

6. Yamba Project Overview

ePub

The best way to learn is by example. After working with thousands of new Android developers and using various example applications to explain some of the unique concepts that this platform has to offer, we have concluded that the best example should meet the following criteria:

The application we picked for this book is a Twitter-like application. We call it Yamba, which stands for Yet Another Micro Blogging App. Yamba lets a user connect to a cloud web service, pull down friends’ statuses, and update his own status.

Yamba covers most of the main Android building blocks in a natural way. As such, it’s a great sample application to illustrate both how various components work individually and how they fit together. Services such as Twitter are more or less familiar to most people, so the features of the application do not require much explanation.

Yamba will not work with Twitter.com, at least not out of the box. We are using the same Twitter API. However, Twitter.com has recently changed to OAuth for its authentication and no longer supports simple (username and password) login. Although we could implement OAuth in Yamba, we felt that doing so dramatically changes our learning objectives and the flow of the material. OAuth would take us on a tangent that is not primary to learning Android development philosophy.

 

7. Android User Interface

ePub

In this chapter, you will learn how to build a user interface in Android. You will create your first activity, create an XML layout for it, and see how to connect it to your Java code. You will learn about views (a.k.a. widgets) and layouts, and learn how to handle Java events, such as button clicks. Additionally, you’ll add support for a Twitter-like API into your project as an external .jar file so your app can make web service calls to the cloud.

By the end of this chapter, you will have written your own Twitter-like Android app. The app will feature a single screen that will prompt the user for her current status update and post that update online.

There are two ways to create a user interface (UI) in Android: declaratively and programmatically. They are quite different but often are used together to get the job done.

The declarative approach involves using XML to declare what the UI will look like, similar to creating a web page using HTML. You write tags and specify elements to appear on your screen. If you have ever handcoded an HTML page, you did pretty much the same work as creating an Android screen.

 

8. Fragments

ePub

In Android 3.0 (API Level 11), Android introduced the Fragments API. This was in response to a growing need to accommodate multiple screen sizes (such as tablets versus phones) and orientations (landscape versus portrait). To do this, it was necessary to modularize the views (the UI) such that it would be easy to separate the Activity container from the UI. This enables the developer to create a more responsive and easy-to-build interface to the user’s needs—such as changing the interface on the fly rather than having to create completely new containers for every configuration.

To show how easy it is to convert an activity into a fragment, let’s start with the StatusActivity we created in a previous chapter. For reference, Example 8-1 is a copy of the old StatusActivity.java file and Example 8-2 is a copy of the layout XML (the activity_status.xml file) for StatusActivity.

To switch to the Fragment API, we need to move the StatusActivity logic into a Fragment extended class. Example 8-3 creates a StatusFragment that extends Fragment and continues to implement OnClickListener and TextWatcher just like the StatusActivity. If you carefully compare the two examples, you will notice that they are extremely similar. This shows just how simple the switch is.

 

9. Intents, Action Bar, and More

ePub

In this chapter, you will learn how to create preferences for your application, how the filesystem is organized, and how to use intents and the options menu to jump from one activity to another.

Preferences are user-specific settings for an application. They usually consist of some configuration data as well as a user interface to manipulate that data.

In the user interface, preferences can be simple text values, checkboxes, selections from a pull-down menu, or similar items. From a data point of view, preferences are a collection of name-value pairs, also known as key-value or attribute-value pairs. The values are basic data types, such as integers, booleans, and strings.

Our micro-blogging application needs to connect to a specific server in the cloud using specific user account information. For that, Yamba needs to know the username and password for that account. So our interface will have two fields where the user can enter and edit the username, and the password. This data will be stored as strings.

 

10. Services

ePub

Services are among the main building blocks in Android. Unlike an activity, a service doesn’t have a user interface; it is simply a piece of code that runs in the background of your application.

Services are used for processes that should run independently of activities, which may come and go. Our Yamba application, for example, needs to create a service to periodically connect to the cloud and check for new statuses from the user’s friends. This service will be always on and always running, regardless of whether the user ever starts the activity.

Just like an activity, a service has a well-defined life cycle. As the developer, you get to define what happens during transitions between states. Whereas an activity’s state is managed by the runtime’s ActivityManager, service state is controlled more by intents. First, you must create the service. Whenever an activity needs the service, the activity will invoke the service through an intent, as described in Intents. This is called starting the service. A running service can receive the start message repeatedly and at unanticipated times. You can also stop a service, which is called destroying it.

 

11. Content Providers

ePub

In this chapter, you will learn about content providers, one of the main building blocks of Android. In a nutshell, think of a content provider as an interface to your app’s data. Before we get to that, we need the data. So, we’ll talk about databases first.

In this chapter, you will learn how Android supports databases. You will learn to create and use a database inside the Yamba application to store your status updates locally. Local data will help Yamba display statuses to the user quickly, without having to wait for the network to provide the data. Our service will run in the background and periodically update the database so that the data is relatively fresh. This will improve the overall user experience of the application.

The Android system uses databases to store useful information that needs to be persisted even when the user kills the app or even shuts down the device and powers it back on. The data includes contacts, system settings, bookmarks, and so on.

So, why use a database in a mobile application? After all, isn’t it better to keep our data in a cloud where it’s always backed up instead of storing it in a mobile device that is easily lost or damaged?

 

12. Lists and Adapters

ePub

In this chapter, you will learn how to create selection widgets, such as a ListView. But this isn’t just a chapter about user interface elements. We are deepening our understanding of data from the previous chapter by learning how to read and use data from the status database. At first we’ll simply output it to the screen as scrollable text. You will then learn about adapters in order to connect your database directly with the list and create a custom adapter to implement some additional functionality. You will link this new activity with your main activity so that the user can both post and read tweets.

By the end of this chapter, your app will be able to post new tweets, as well as pull them from Twitter, store them in the local database, and let the user read the statuses in a nice and efficient UI. At that point, your app will have three activities and a service.

We’re going to create a new MainActivity. This activity will become the entry point into the application and for the most part will contain the TimelineFragment that will pull the data from the content provider and show it to the user.

 

13. Broadcast Receivers

ePub

In this chapter, you will learn about broadcast receivers and when to use them. We’ll create a couple of different receivers that illustrate different usage scenarios. First, you’ll create a broadcast receiver that will set up the alarms to autostart your refresh timeline service every so often.

Next, you will create a receiver that will be notified when there’s a new tweet, and post that notification to the user.

In this chapter, in addition to using broadcast receivers, you will also learn how to take advantage of Android’s OS system services.

By the end of this chapter, your app will have most of the functionality that a user would need. The app can send status updates, get friends’ timelines, update itself, and start automatically. It works even when the user is not connected to the network (although of course it cannot send or receive new messages).

Broadcast receivers are Android’s implementation of the publish/subscribe messaging pattern, or more precisely, the observer pattern. Applications (known as publishers) can generate broadcasts to simply send events without knowing who, if anyone, will get them. Receivers (known as subscribers) that want the information subscribe to specific messages via filters. If the message matches a filter, the subscriber is activated (if it’s not already running) and notified of the message.

 

14. App Widgets

ePub

In Android, the idea of showing mini application views embedded in other applications, the most common case being that of the home screen, is a very important and useful feature. These are called app widgets, or widgets for short. These widgets not only provide a small window into an easily accessible view, but also can receive updates and thus provide a more dynamic experience to your application.

As mentioned before, content providers make the most sense when you want to expose the data to other applications. It is a good practice to always think of your application as part of a larger Android ecosystem and, as such, a potential provider of useful data to other applications.

To demonstrate how content providers can be useful, we’ll create a home screen widget. We’re not using the term widget here as a synonym for Android’s View class, but as a useful embedded service offered by the home screen.

Android typically ships with a few home screen widgets. You can access them by going to your home screen, long-pressing on it to pull up an Add to Home Screen dialog, and choosing Widgets. Widgets that come with Android include Alarm Clock, Picture Frame, Power Controls, Music, and Search. Our goal is to create our own Yamba widget that the user will be able to add to the home screen.

 

15. Networking and Web Overview

ePub

Networking is one of the fundamental tasks of mobile development. In today’s world, the power of the smartphone lies not so much in its computational abilities as in its connections to the greater collection of servers and clients that make up the Internet. Understanding the role of networking within the Android development environment is critical. With this in mind, this chapter will cover a common form of networking: sending web data over HTTP.

Let us do a quick simple example of an HTTP network connection to give an idea of what we are going to cover. First, copy the code in Example 15-1 to a file called QuickHttpExample.java and run it (Example 15-2). This will produce the output as shown in Example 15-3 (we truncated the output because it is very long). What this example does is creates an HTTP connection to http://yamba.marakana.com/api/statuses/public_timeline.json (if you copy this URL into a browser you will see some very long data that is similar to the long output in the output of the program). It then proceeds to check the response status (getResponseCode()), read in the server’s output, and write that out to the system console. It terminates the connection after it is done (disconnect()).

 

16. Interaction and Animation: Live Wallpaper and Handlers

ePub

This chapter covers the animated LiveWallpaper API that allows developers to create interactive wallpaper that users may choose to run as part of their home page. We also cover handlers, an essential part of the Android thread system that enhances interactivity.

Android 2.1 (API Level 7) introduced live wallpaper. A live wallpaper is a wallpaper (a background set on the home screen) that may be animated and enabled for interaction. It has access to the other services and APIs as normal Android applications: network, GPS, etc. The primary class to use when creating a live wallpaper is the LiveWallpaperService (located in android.service.wallpaper.WallpaperService).

For an example, we will put together a live wallpaper that is touch-enabled and utilizes the Internet (via the Yamba Manager) in order to place some text at the point of touch. To do this, you must add a service definition within the main Manifest (see Example 16-1). Next, create a Service Resource (see Example 16-2).

 

Details

Print Book
E-Books
Slices

Format name
ePub
Encrypted
No
Sku
9781449336257
Isbn
9781449336257
File size
0 Bytes
Printing
Not Allowed
Copying
Not Allowed
Read aloud
No
Format name
ePub
Encrypted
No
Printing
Allowed
Copying
Allowed
Read aloud
Allowed
Sku
In metadata
Isbn
In metadata
File size
In metadata