Drawing the Board

Android calls a view's onDraw() method every time any part of the view needs to be updated. To simplify things, onDraw( ) pretends that you're re-creating the entire screen from scratch. In reality, you may be drawing only a small portion of the view as defined by the canvas's clip rectangle. Android takes care of doing the clipping for you. Start by defining a few new colors to play with in res values colors.xml Download Sudokuv2 res values colors.xml < color < color < color < color...

Why Does Android Use XML Isnt That Inefficient

Android is optimized for mobile devices with limited memory and horsepower, so you may find it strange that it uses XML so pervasively. After all, XML is a verbose, human-readable format not known for its brevity or efficiency, right Although you see XML when writing your program, the Eclipse plug-in invokes the Android resource compiler, aapt, to prepro-cess the XML into a compressed binary format. It is this format, not the original XML text, that is stored on the device. Next we see a...

Where Am I

Start by creating a Hello, Android application using these parameters in the New Project wizard Project name LocationTest Build Target Android 2.2 Application name LocationTest Package name org.example.locationtest Create Activity LocationTest Min SDK Version 8 Access to location information is protected by Android permissions. To gain access, you'll need to add these lines in the AndroidManifest.xml file before the < application> tag Download LocationTest AndroidManifest.xml > <...

Embedding a Map View

A MapView can be embedded directly in your Android application with just a few lines of code. Most of the functionality of Google Maps, plus hooks for adding your own touches, is provided (see Figure 8.3, on the following page). The MapView class can also tie into your location and sensor providers. It can show your current location on the map and even display a compass showing what direction you're heading. Let's create a sample program to demonstrate a few of its capabilities. First create a...

Hello Widget

Introduced in Android 1.5 (Cupcake), widgets are miniature application views that can be embedded in the Home screen. A few widgets are provided with Android including an analog clock, a music controller, and one that just shows a picture. Many developers have created interesting widgets to display the weather, news headlines, horoscopes, and more, and you can too. This section will show you how. For this example we're going to create a widget that shows today's date. If you'd like a peek at...

Creating the Opening Screen

We'll start with a skeleton Android program created by the Eclipse plugin. Just as you did in Section 1.2, Creating Your First Program, on page 23, create a new Hello, Android project, but this time use the following values Project name Sudoku Build Target Android 2.2 Application name Sudoku Package name org.example.sudoku Create Activity Sudoku Min SDK Version 8 In a real program, of course, you would use your own names here. The package name is particularly important. Each application in the...

Adding Options to Sudoku

In Section 3.7, Adding a Menu, on page 64, we used the onCreateOption-sMenu() method to add a menu containing one item to the main Sudoku screen. When the user presses the Menu key and selects the Settings item, the code starts the Prefs activity, which lets the user change the options for the game. Because Prefs extends PreferenceActivity, the values for the settings are stored in the program's preferences area, but originally we didn't do anything with them. Now we're going to implement them....

Using SQLite OpenHelper

Next we create a helper class called EventsData to represent the database itself. This class extends the Android SQLiteOpenHelper class, which manages database creation and versions. All you need to do is provide a constructor and override two methods. Download - import static android.provider.BaseColumns._ID - import static 5 import static org.example.events.Constants.TIME - import static org.example.events.Constants.TITLE - import android.content.Context - import - public class EventsData...

Data Binding

Data binding allows you to connect your model (data) to your view with just a few lines of code. To demonstrate data binding, we'll modify the Events example to use a ListView that is bound to the result of a database query. First, we need to make the Events class extend ListActivity instead of Activity Download public class Events extends ListActivity Next, we need to change how the events are displayed in the Events. showEvents( ) method Download import android.widget.SimpleCursorAdapter...

Rendering the Scene

As we saw in Section 4.2, Drawing the Board, on page 83, the Android 2D library calls the onDraw( ) method of your view whenever it needs to redraw a section of the screen. OpenGL is a bit different. In OpenGL ES on Android, drawing is separated into a rendering class that is responsible for initializing and drawing the entire screen. Let's define that now. Here's the outline for the GLRenderer class Download import import import android.content.Context import android.opengl.GLSurfaceView...

Installing on the SD Card

Starting in Android 2.2, you can specify that your application may be installed on the SD card instead of on the phone's limited internal memory. 9. See for a full explanation of how Android finds the best matching directory. To do that, add the android installLocation attribute to the < manifest> tag in your AndroidManifest.xml file like this < manifest Valid values are auto and preferExternal. I recommend you use auto, which lets the system decide where it should go. Specifying...

Defining the Puzzle View Class

Next we need to define the PuzzleView class. Instead of using an XML layout, this time let's do it entirely in Java. Download from Library of Wow eBook < www.wowebook.com> A common mistake made by new Android developers is to use the width and height of a view inside its constructor. When a view's constructor is called, Android doesn't know yet how big the view will be, so the sizes are set to zero. The real sizes are calculated during the layout stage, which occurs after construction but...

Evolving with Android APIs

Sometimes you need to use an API that does not appear in all versions of Android. For instance, in the touch example (Chapter 11, Multi-Touch, on page 220), we used some new methods of the MotionEvent class that were not there before Android 2.0. If you try to run that example in the em16 emulator, you will get the error in Figure 13.1. If you then open the LogCat view in Eclipse (Window > Show View > Other > Android Log) and scroll back a little, you'll find a more detailed error...

Creating the Keypad

The keypad is handy for phones that don't have keyboards. It displays a grid of the numbers 1 through 9 in an activity that appears on top of the puzzle. The whole purpose of the keypad dialog box is to return a number selected by the player. Here's the user interface layout from res layout keypad.xml Download Sudokuv2 res layout keypad.xml lt xml version 1.0 encoding utf-8 gt android orientation vertical android layout_width 'wrap_content android layout_height 'wrap_content lt Button android...

Understanding Touch Events

Whenever I first learn a new API, I like to first put in some code to dump everything out so I can get a feel for what the methods do and in what order events happen. So let's start with that. First add a call to the dumpEvent method inside onTouch Download public boolean onTouch View v, MotionEvent event Dump touch event to log dumpEvent event return true indicate event was handled Note that we need to return true to indicate to Android that the event has been handled. Next, define the...

Playing Audio

It was a dark and stormy night There goes the starting shot, and they're off The crowd goes wild as State sinks a three-pointer with one second remaining Audio cues permeate the environment and set the tempo for our emotions. Think of sound as another way to get into your user's head. Just like you use graphics on the display to convey some information to the user, you can use audio to back that up and reinforce it. Android supports sound and music output through the MediaPlayer class in the...

Joe Asks

Some low-end devices running Android may not actually have 3D hardware. However, the OpenGL programming interface will still be there. All the 3D functions will be emulated in software. Your program will still run, but it will be much slower than a hardware-accelerated device. For this reason, it's a good idea to provide options for users to turn off certain details and special effects that take time to draw but aren't absolutely necessary for the program. That way, if the user is...

Live Wallpaper

It looks nice, but it never changes. Yawn. 2. Figure 12.6 The wallpaper example reuses code from the OpenGL chapter. Live wallpaper is a new feature in Android 2.1 Eclair Maintenance Release 1 . It lets you replace boring static wallpaper images with everything from vibrant and pulsing music visualizations to quiet, meditative ponds that respond to your touch with gentle ripples. Displaying current weather conditions, slide shows, Magic 8 Balls, and...

Storing Local Data

So far, we've concentrated on writing applications that don't need to keep data around when they exit. They start up, run, and go away, leaving no trace that they were ever there. However, most real programs need persistent state, whether it's a simple font size setting, an embarrassing photo from your last office party, or next week's meal plan. Whatever it is, Android lets you permanently store it on your mobile device for later use and protects it from accidental or malicious access by other...

Continuing an Old Game

At any time the player can decide to quit playing our Sudoku game and go do something else. Maybe their boss walked in, or they got a phone call or a notification of an important appointment. Whatever the reason, we want to allow the player to come back later and continue where they left off. First we need to save the current state of the puzzle somewhere. The preferences API can be used for more than just options it can store any small stand-alone bits of information that go with your program....

Creating an AVD

To do this, you need to create an Android Virtual Device AVD using either Eclipse or the android avd command.6 It's easier to use Eclipse, so select Yes in the AVD Error dialog to open the AVD Manager. You can open the manager again later by selecting Window gt Android SDK and AVD Manager. 6. Creates a new Android Project resource. Create project from existing source 13 Use default location Location C Development wo rkspa ce-''H el 1-oAndrord Create project from existing sample Standard Android...

Applying Texture

Although the scene is starting to look more interesting, nobody would mistake it for real life. Everyday objects have textures, like the rough surface of a brick wall or the gravel on a garden path. Do you own a laminated table A wood laminate is just a photograph of wood grain that is glued on the surface of a less expensive material like plastic or particle board. The first version of this example kept track of the current rotation angle and simply incremented it each time through the loop....