




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































Available as a PDF Electronic Book or Print On Demand
Apress's firstPress series is your source for understanding cutting-edge technology. Short, highly focused, and written by experts, Apress's firstPress books save you time and effort. They contain the information you could get based on intensive research yourself or if you were to attend a conference every other week—if only you had the time. They cover the concepts and techniques that will keep you ahead of the technology curve. Apress's firstPress books are real books, in your choice of electronic or print-on-demand format, with no rough edges even when the technology itself is still rough. You can't afford to be without them.
Dear Reader,
This book covers the essential information required to build an Android application. It will help any developer, amateur, professional, or dabbler who is interested in developing for Android. Over the course of the book, I cover the essentials you’ll need to get started with your own innovative application. I took on this project because, after five years of working in the mobile software industry, it has become clear that we need help. With mobile devices becoming more ubiquitous, powerful, and, indeed, essential, fresh blood is necessary to overcome the stagnation that has plagued our business. As an industry, we need to graduate from making cookie-cutter ringtones, wallpaper, and e-mail applications. I hope, once you’ve finished this book, that you’ll be in a position to start that killer mobile product you’ve told all your friends you’re going to make. In Android Essentials , I cover the details of installing and using the Android SDK, making and rendering user interface tools, harnessing location tracking and Google Maps, and putting everything together with a little glue from XML parsers and networking clients. These tools and tricks should be enough to get you past your empty editor, the daunting blank canvas of the developer world, and onto the path of your own innovative mobile app. Android potentially represents our best hope for a break from the constricted world of mobile development. Use it to make something amazing. I can’t wait to see what you create.
Regards, Chris Haseman Lead software engineer at Gravity Mobile
Chapter 1: Introduction
Before you start, we’ll need to have a quick discussion about where you’re beginning.
What You Need to Know to Start
It is a natural question you may be asking yourself: is this book for you? Yes, obviously, it is because you’re reading it. However, I will make a few assumptions about your abilities:
You understand Java; you can write it, read it, and grok it. Because this book is about the Android platform and not the language, I will be writing large amounts of Java code inline and assuming you can follow along. If your Java skills are rusty, I recommend checking out Apress’s wealth of Java information on its site (http://java.apress.com/).
Some familiarity with other mobile platforms will help you. As you move through the book, I’ll make comparisons between Android and other mobile software development kits (SDKs). You don’t need to be a professional mobile developer to follow along by any means.
You have superior hacker skills. OK, not really, but if you’re comfortable rolling up your proverbial sleeves and digging into the heart of a problem, you should feel right at home with this book.
I will assume you have exactly zero experience developing for Android. If you’ve already mastered the basics, you may want to skip the first chapter and focus on the more advanced topics that follow.
That wasn’t a big list, but it contained a few things that will help you follow the book with your sanity intact.
Ideally, I want this book to be useful and valuable to anyone interested in developing applications for Android. Hobbyists will find a foundation here for their dream application. Mobile game developers will find the nuts and
bolts of graphical output and user input. Multimedia and application developers will find all the tricks, tips, and core functionality they need to put together the next major killer app. If you’re a business-oriented person looking into porting your existing applications to Android, you’ll find invaluable information on how to accomplish exactly that. In short, this book has a lot to offer you no matter your desired outcome, experience, time, or interest.
How to Best Use This Book
The simple answer is to read it, but this may mean different things to different people. If you’re new to mobile development and Android, it would be best for you to treat this book as a tutorial. Follow along, chapter by chapter, until you have all the basics you need to get working.
If you’re a more experienced Java and mobile programmer but are inexperienced with Android, you might want to treat this book as more of a reference manual after going through the first chapter to get a feel for things.
Throughout this work, I will primarily use real-world examples as a means to get you comfortable with Android. This book may not have a huge appeal to those who are already established veteran Android developers. As I said before, I will start from a place that assumes no prior experience with this SDK. This book will start simple: a splash screen, a main menu, and some simple multimedia. I’ll then get into the more advanced concepts of Bluetooth, location-based services, background applications, and the other exciting features Android has to offer.
Enough talking, it’s time to start.
Getting Started
It begins with installing the SDK. On a personal note, I’m doing all my development on Mac OS X with Eclipse. All screenshots, IDE information,
where it is later. It’s also a good idea, if you’re a Windows or Linux user, to add the location of the Android tools to your Path variable.
I like graphical user interfaces (GUIs), provided they have hotkeys like the Eclipse IDE, when working with Android. To get more than basic functionally out of the process, you’ll need to download the Android Developer Tools. To install it from within Eclipse, follow the directions outlined by Google at http://code.google.com/android/intro/
installing.html#installingplugin.
If you’ve already installed the older version of the SDK and the Eclipse plug-in, I recommend you go back and update it to M5-RC15 (or the latest version) now using the previously mentioned links. Enough has changed between the older version and the latest that the changing details could be confusing. If you correctly follow the directions but get an error when trying to install the Android editors, go back and install the full version of Java EE Eclipse. The basic Java SDK doesn’t include all the correct packages used by the Android plug-in.
Don’t forget to point the Android plug-in to where you unpacked your copy of the SDK. It’ll be in Windows/Preferences/Android on the Android tab.
Create a new project by selecting File h New h Android Project. Give the project and activity a pithy name of your choosing. You’ll also have to insert into your source package name at least one dot (.), such as apress. book.sample or crazy.flyingmonkey.application.
Eclipse gives a fairly unhelpful error message if you forget to give it more than one name separated by dots. I can personally testify that this can be fairly frustrating if your brain is fried and you’re, say, trying to get a book done on a deadline.
The Android Project
So, you’re now the proud owner of your own basic Android application. If this isn’t the case, because you skipped the previous section, create a new project right now. New projects, by default, have an implementation of “Hello, World.” Books and articles that start by explaining “Hello, World” aren’t particularly useful in my humble opinion. Consequently, I’m not going to take your time breaking down the functionality of the most basic Android application. What is worth taking some time to look into, however, are the contents, layout, and files of your new project. Let me briefly explain how each file and directory contributes to a functioning Android project (see Table 1-1).
Table 1-1. Files in a Basic Android Project
FILE NAME PURPOSE
YourActivity.java (^) File for your default launch activity; more on this to follow. R.java (^) File containing an ID for all asset constants. Android Library/ (^) Folder containing all Android’s SDK files. assets/ (^) Multimedia and other miscellaneous required files. res/ (^) Base directory for resources used by the UI. res/drawable (^) Directory for image files to be rendered by the UI layer. res/layout (^) All XML-style view layout files are stored here. Again, more on this later.
Continued
After the xml/declaration comes the
Next up is the application declaration and location of the application icon. The @drawable notation indicates that the item can be found in the res/drawable folder. The application, at this point, consists of a single activity: SampleApp. The activity name is hard-coded, but its label, or what is displayed to the user within the Android application menu, is defined in the res/values/strings.xml file. The @string notation pulls the value from app_name within the aforementioned XML file.
Now you come to the intent filter. I will go into intent filters at length in the next chapter, but for now, you need to know that android.intent. action.MAIN and android.intent.category.LAUNCHER are predefined strings that tell Android which activity to fire up as your application is started.
That’s all there is to the manifest file in its most basic form. For space reasons, I will try to avoid writing out the entire manifest file again. If you need context for elements that are being inserted later, dog-ear this page and return to it later.
Note Get in the habit of moving as many strings, resources, and screen layouts into the res folder as much as humanly possible. It may cost you a little more time to work from these files up front, but once you start porting your application to the different languages, screen sizes, and function sets, your prep time will be paid back with interest. I’m sure this is something you read in computer manuals constantly, but it bears repeating. A little bit of planning and overhead up front can save you weeks of porting and debugging on the back side of a project. This is particularly important when developing for mobile devices, because each application can have many separate build environments.
Next up on the important file list is R.java. This file is where reference identification numbers live for all your resources, both graphical and drawable. Adding a new graphic to res/drawable should result in a corresponding identifier in the R.java class. References can then be made to these IDs rather than the items on the filesystem. This allows you to swap out strings for localization, screen size, and other errata that are guaranteed to change between devices.
You’ll get into the other files as you add functionality to your repertoire. Let’s get your application up and running.
Running, Debugging, and Causing General Mayhem
Running and debugging are, thankfully, extremely straightforward with Android. From within Eclipse, pull down the Run menu and select…wait for it…Run. This launches the Android emulator.
Tip Once you’ve started the emulator for the first time, you don’t need to quit or close it down. The latest version of the SDK ships with an emulator that can take minutes to “boot up.” While the emulator is running, each subsequent Run or Debug execution will build and deploy your latest code to the emulator. The emulator will accept the changes and automatically launch your new project. This is the opposite of BREW or J2ME, which must relaunch after each change in your source base.
Once the Android emulator is up and running, you should see the “Hello World, YourApplicationName ” message.
Again, “Hello, World” as a programming example is, for lack of a better term, emphatically lame, so I’ll skip it and move on to a more practical example: a simple splash screen. Along the way, you should come to understand activities, intents, intent filters, services, and content providers.
Android applications can have any number of activities registered with the handset through the AndroidManifest.xml file. Android’s multiactivity architecture is probably the major difference between developing for Android and developing for other handset SDKs. This single fact makes it much easier to write modular, compartmentalized code. In BREW and Java ME, a developer will implement most functionality within the confines of the midlet or the applet. In Android, you can write an activity, content handler, intent receiver, or service to handle nearly anything. Once you’ve written an activity to edit a text file, you can refer to this activity in all future applications you write by sending and receiving intent actions. This isn’t to say that such architecture isn’t possible within BREW or Java ME. It just has to be done at the Java, C, or C++ level or, in Brew, with cumbersome extensions instead of being built smoothly into the application framework.
Functionality
Just like the midlet, an activity uses a series of functions to interact with the outside world. At its base, your activity must override the method onCreate. Other functions you’ll want to override are onStop, onPause, onResume, and onKeyDown. These few functions are what will let you tie your activity into the Android handset at large.
By default, new Android applications created within Eclipse will implement a “Hello, World” application. I’ll show you how to go from this basic application to a fully functional splash screen.
You can download the packaged version of this splash screen example from the downloads section of www.apress.com if you want to use it as a starting point for your own Android application or you want to follow along in a more passive fashion. In this example, because it is your first, I will go through it in a series of small steps. I’ll break down exactly what
needs to be written, from adding a new image resource to modifying XML layout files. Down the road, examples will not parse out into such minute detail. This should be the only chapter that will read like a tutorial for beginners.
Adding the Image Resource
First you’ll need a sample splash screen image. The “socially awkward” splash screen I’ve included is not going to win any awards, but it is a good poke at the rash of social networking applications that seem to keep cropping up in the mobile space right now.
To add this new resource, I’ve placed menu_background.jpg inside res/drawable. Make sure a new ID is added to R.java. It should look something like this:
public static final int menu_background=0x7f020001;
This is now your means of loading and drawing the image from within your code. You’ll return to this concept in the next chapter on user interaction.
Creating an XML Layout File
Now that you have an image resource, you can add it to your XML layout file. These files are kept in res/layout/, and you should currently have one called main.xml. Add a new XML file called splash.xml, and copy the contents of the main.xml file into it. Next, modify the file by removing the
Using Android’s XML layout objects is simple and straightforward. As I mentioned, files in the /res directories can be referenced with the @
boolean m_bSplashActive = true ;
public void onCreate(Bundle icicle) { super .onCreate(icicle);
//Draw the splash screen setContentView(R.layout.splash); //Very simple timer thread Thread splashTimer = new Thread() { public void run() { try { //Wait loop long ms = 0; while (m_bSplashActive && ms < m_dwSplashTime) { sleep(100); //Advance the timer only if we're running. if (!m_bPaused) ms += 100; } //Advance to the next screen. startActivity( new Intent( "com.google.app.splashy.CLEARSPLASH")); } catch (Exception e) { Log.e("Splash", e.toString()); } finally { finish(); } } }; splashTimer.start(); }
At long last, you’re getting into some Java code. This simple thread will run until the time counter exceeds m_dwSplashTime. Although there are other methods for implementing a timer, I like this one for two reasons:
It can be paused. The timer will advance only if the m_bPaused flag is false. As you’ll see in a minute, it’s easy to suspend the timer if your activity’s onPause method is called. This is not always a requirement for a splash screen, but it is important for other timing-based operations.
Moving to the next screen is as simple as flipping the m_bSplashActive flag to false. Advancing to the next screen, if you implement it in this fashion, does not require you to make the move and then cancel a more traditional timer.
With this code in place, you should see the splash screen for as long as you set m_dwSplashTime in milliseconds. When that time is up or the user interrupts the splash screen with a key press, startActivity will be called (I’ll explain this shortly). This function will move the user to what will become the main menu in the next chapter. finish closes down the splash activity so the user does not return to it when they press Back from the main menu. You’ll need to implement an activity that accepts the CLEARSPLASH intent action. In the meantime, let’s review a few other important activity methods you’ll want to override.
Pause, Resume, Rinse, Repeat
Pausing the splash timer when your activity is suspended by an incoming call, SMS message, or other interruption is as easy as the following:
protected void onPause() { super.onPause(); m_bPaused = true; }