From Java Script to Java and Back

Your Android device can do a number of cool things such as store local data, draw graphics, play music, make calls, and determine its location. Wouldn't it be nice if you could access that functionality from a web page With an embedded WebView control, you can. The key is the addJavascriptInterface() method in the WebView class. You can use it to extend the Document Object Model (DOM) inside the embedded browser and to define a new object that JavaScript code can access. When the JavaScript...

Remembering the Current Position

If you change the screen orientation while Sudoku is running, you'll notice that it forgets where its cursor is. That's because we use a custom PuzzleView view. Normal Android views save their view state automatically, but since we made our own, we don't get that for free. unlike persistent state, instance state is not permanent. It lives in a Bundle class on Android's application stack. Instance state is intended to be used for small bits of information such as cursor positions. Here's what we...

Building for Multiple Versions

First, we'll try running the Hello, Android program from Section 1.2, Creating Your First Program, on page 23 in the 1.6 emulator. From the menu, select Run > Run Configurations. Locate the configuration for HelloAndroid and select it, or create a new Android Application configuration if it doesn't exist. Click the Target tab, and set Deployment Target Selection Mode to Manual. Then click the Run button. Eclipse will show a dialog asking you to choose a running Android device. You may notice...

Implementing the Pinch Zoom Gesture

The pinch zoom gesture is similar, except it starts when the second finger is pressed to the screen (ACTION_POINTER_DOWN). Download case MotionEvent.ACTI0N_P0INTER_D0WN oldDist spacing(event) Log.d(TAG, oldDist + oldDist) if (oldDist > 10f) savedMatrix.set(matrix) midPoint(mid, event) mode ZOOM case MotionEvent.ACTI0N_M0VE if (mode DRAG) float newDist spacing(event) Log.d(TAG, newDist + newDist) if (newDist > 10f) matrix.postScale(scale, scale, mid.x, mid.y) When we get the down event for...

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...

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...

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....

Joe Asks

Shouldn't We Use a Background Service for Music We haven't said much about the Android Service class, but you may have seen it used in some music-playing examples on the Web. Basically, a Service is a way to start a background process that can run even after your current activity finishes. Services are similar to, but not quite the same as, Linux daemons. If you're writing a general-purpose music player and want the music to continue while you're reading mail or browsing the Web, then, yes, a...

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....