List Controls

The Android SDK offers several list controls. Figure 4-6 shows a ListView control that we'll discuss in this section. The ListView control displays a list of items vertically. You generally use a ListView by writing a new activity that extends android.app.ListActivity. ListActivity contains a ListView, and you set the data for the ListView by calling the setListAdapter method. Listing 4-17 demonstrates this. Figure 4-6. Using the ListView control Figure 4-6. Using the ListView control Listing...

Getting an EGL Context

In the Android SDK distribution, the EGL API is available in the package javax.microedition. khronos.egl.EGL10. You can read more about using this package at http java.sun.com Note Although this URL points to a web site about Java, it's relevant because Android uses the same API. All of the site's information on EGL is applicable to Android OpenGL programming as well. Getting an EGL context involves the following steps 1. Get an implementation of EGL10. 4. Specify a device-specific...

Using Camera to Provide Depth Perception in 2D

The graphics package in Android provides another animation-related or more accurately, transformation-related class called Camera. You can use this class to provide depth perception by projecting a 2D image moving in 3D space onto a 2D surface. For example, you can take our ListView and move it back from the screen by 10 pixels along the z axis and rotate it by 30 degrees around the y axis. Here is an example of manipulating the matrix using a Camera protected void applyTransformation float...

Some Notes on Transformation Matrices

As you have seen in this chapter, matrices are key to transforming views and animations. We will now briefly explore some key methods of the Matrix class. These are the primary operations on a matrix The first operation resets a matrix to an identity matrix, which causes no change to the view when applied. setScale is responsible for changing size, setTranslate is responsible for changing position to simulate movement, and setRotate is responsible for changing orientation. setSkew is...

Grid Controls

Most widget toolkits offer one or more grid-based controls. Android has a GridView control that can display data in the form of a grid. Note that although we use the term data here, the contents of the grid can be text, images, and so on. The GridView control displays information in a grid. The usage pattern for the GridView is to define the grid in the XML layout see Listing 4-20 , and then bind the data to the grid using an android.widget.ListAdapter. Listing 4-20. Definition of a GridView in...

A

AbsoluteLayout layout manager, 141-142 AbstractRenderer source code OpenGL , 396-397 AbstractRenderer.java, 345, 354-355 ACTION_GET_CONTENT action, 104-105 ACTION_PICK action, 102-104 actions, generic, 95 activities activity.onCreateContextMenu method, 165 method, 166 adding animation to, 201-204 categories, 100 code for layout animation, 207-208 components to invoke, 97-98 creating, 199-200, 206-208 defined, 10, 24 lifecycle methods of, 39 live folders and, 410 state transitions of, 40-41...

Changing Camera Settings

To understand the coordinates better, let us experiment with the camera-related methods and see how they affect the triangle that you drew. Remember that these are the points of our triangle -0.5,-0.5,0 0.5,-0.5,0 0,0.5,0 . The following three camera-related methods yield the triangle as it appears in Figure 10-3 Look at the screen origin from 5 units away from the front of the screen GLU.gluLookAt gl, 0,0,5, 0,0,0, 0,1,0 Set the height to 2 units and depth to 4 units gl.glFrustumf -ratio,...

Basic Tweening Animation Types

Before we design the test harness to apply the various tweening animations, we'll give you some detail on the basic types of tweening animation Scale animation You use this type of animation to make a view smaller or larger either on the x axis or on the y axis. You can also specify the pivot point around which you want the animation to take place. Rotate animation You use this to rotate a view around a pivot point by a certain number of degrees. Translate animation You use this to move a view...

The RadioButton Control

Radio-button controls are an integral part of any UI toolkit. A radio button gives the user several choices and forces her to select a single item. To enforce this single-selection model, radio buttons generally belong to a group and each group is forced to have only one item selected at a time. To create a group of radio buttons in Android, first create a RadioGroup and then populate the group with radio buttons. Listing 4-15 and Figure 4-5 show an example. Listing 4-15. Using Android...

Setting Up an AlertDialog Builder with a User View

Let's combine steps 2 through 4 from our instructions to create a prompt dialog loading the XML view and setting it up in the alert-dialog builder. Android provides a class called android. view.Layoutlnflater to create a View object from an XML layout definition file. We will use an instance of the Layoutlnflater to populate the view for our dialog based on the XML layout file see Listing 5-23 . Listing 5-23. Inflating a Layout into a Dialog Layoutlnflater li Layoutlnflater.from ctx View view...

Exploring the MediaStore Class

The MediaStore class provides an interface to the media that is stored on the device in both internal and external storage . MediaStore also provides APIs for you to act on the media. These include mechanisms for you to search the device for specific types of media, intents for you to record audio and video to the store, ways for you to establish playlists, and more. Note that this class was part of the older SDKs, but it has been greatly improved with the 1.5 release. Because this class...

Working with the Telephony Manager

The telephony APIs also include the telephony manager android.telephony.TelephonyManager , which you can use to obtain information about the telephony services on the device, get subscriber information, and register for telephony state changes. A common telephony use case requires that an application execute business logic upon incoming phone calls. So in this section, we are going to show you how to register for telephony state changes and how to detect incoming phone calls. Listing 9-9 shows...

Simplifying OpenGL

The OpenGL-related changes in the Android 1.5 SDK are primarily aimed at providing a simplified interface to the OpenGL drawing capabilities. This simplification will make OpenGL a lot more approachable to beginning OpenGL programmers. We discussed this need in Chapter 10, and to address it, we designed an OpenGL test harness that exhibits the following characteristics Hide how one needs to initialize and get an EGLContext Hide the complexities of drawing on a SurfaceView using a secondary...

Adding Animation to the Activity

Now that you have the activity and layout in place, we'll show you how to add animation to this sample. In Android, you accomplish frame-by-frame animation through a class in the graphics package called AnimationDrawable. This class can take a list of Drawable resources like images and render them at specified intervals. This class is really a thin wrapper around the animation support provided by the basic Drawable class. The Drawable class enables animation by asking its container or view to...

Exploring Voice Recognition

Android 1.5 includes a voice-recognition framework, and one of its popular toys is the Recognizerlntent class. The activity class in Listing 12-5 demonstrates this intent. Listing 12-5. Using the RecognizerIntent import java.util.List import android.speech.Recognizerlntent import android.view.View.OnClickListener public class RecognizeSpeechActivity extends Activity Called when the activity is first created. Override public void onCreate Bundle savedInstanceState super.onCreate...

Using the HttpClient for HTTP POST Requests

Making an HTTP POST call is very similar to making an HTTP GET call see Listing 8-3 . Listing 8-3. Making an HTTP POST Request with the HttpClient import java.util.ArrayList import java.util.List import org.apache.http.HttpResponse import org.apache.http.NameValuePair import org.apache.http.client.HttpClient import import import import public String executeHttpPost throws Exception BufferedReader in null try HttpClient client new DefaultHttpClient HttpPost request new HttpPost List lt...

Using Overlays

Google Maps provides a facility that allows you to place custom data on top of the map. You can see an example of this if you search for pizza restaurants in your area Google Maps places pushpins, or balloon markers, to indicate each location. The way Google Maps provides this facility is by allowing you to add a layer on top of the map. Android provides several classes that help you to add layers to a map. The key class for this type of functionality is Overlay, but you can use an extension of...

M3G Another Java ME 3D Graphics Standard

JSR 239 is merely a Java binding on a native OpenGL ES standard. As we mentioned briefly in the OpenGL ES subsection, Java provides another API to work with 3D graphics on mobile devices M3G. This object-oriented standard is defined in JSR 184 and JSR 297, the latter being more recent. As per JSR 184, M3G serves as a lightweight, object-oriented, interactive 3D graphics API for mobile devices. The object-oriented nature of M3G separates it from OpenGL ES. For details, visit the home page for...

Geocoding with Android

If you are going to do anything practical with maps, you'll likely have to convert an address or location to a latitude longitude pair. This concept in known as geocoding, and the android. location.Geocoder class provides this facility. In fact, the Geocoder class provides both forward and backward conversion it can take an address and return a latitude longitude pair, and it can translate a latitude longitude pair into a list of addresses. The class provides the following methods List lt...

Structure of android Content URIs

We compared a content provider to a web site because it responds to incoming URIs. So, to retrieve data from a content provider, all you have to do is invoke a URI. The retrieved data in the case of a content provider, however, is in the form of a set of rows and columns represented by an Android cursor object. In this context, we'll examine the structure of the URIs that you could use to retrieve data. Content URIs in Android look similar to HTTP URIs, except that they start with content and...

TextView

The TextView control knows how to display text but does not allow editing. This might lead you to conclude that the control is essentially a dummy label. Not true. The TextView control has a few interesting properties that make it very handy. If you know that the content of the TextView is going to contain a web URL, for example, you can set the autoLink property to web and the control will find and highlight the URL. Moreover, when the user clicks the TextView, the system will take care of...

Understanding the setDataSource Method

In Listing 9-2, we called the create method to load the audio file from a raw resource. With this approach, you don't need to call setDataSource . Alternatively, if you instantiate the MediaPlayer yourself using the default constructor, or if your media content is not accessible through a resource ID or a URL, you'll need to call setDataSource . The setDataSource method has overloaded versions that you can use to customize the data source for your specific needs. For example, Listing 9-3 shows...

Understanding MapView and MapActivity

A lot of the mapping technology in Android relies on the MapView UI control and an extension of android.app.Activity called MapActivity. The MapView and MapActivity classes take care of the heavy lifting when it comes to displaying and manipulating a map in Android. One of the things that you'll have to remember about these two classes is that they have to work together. Specifically, in order to use a MapView, you need to instantiate it within a MapActivity. In addition, when instantiating a...

Geocoding with Background Threads

Using background threads to handle time-consuming operations is very common. The general pattern is to handle a UI event such as a button click to initiate a timely operation. From the event handler, you create a new thread to execute the work and start the thread. The UI thread then returns to the user interface to handle interaction with the user, while the background thread works. After the background thread completes, a part of the UI might have to be updated or the user might have to be...

IDialogFinishedCallBack

The IDialogFinishedCallBack interface allows the ManagedActivityDialog class to tell the parent activity that the dialog has finished and that the parent activity can call methods on the dialog to retrieve parameters. Usually a ManagedDialogsActivity implements this interface and acts as a parent activity to the ManagedActivityDialog see Listing 5-32 . Listing 5-32. The IDialogFinishedCallBack Interface public interface IDialogFinishedCallBack public static int OK_BUTTON -1 public static int...

EditText

The EditText control is a subclass of TextView. As suggested by the name, the EditText control allows for text editing. EditText is not as powerful as the text-editing controls that you find in JFC, for example, but users of Android-based devices probably won't type documents they'll type a couple paragraphs at most. Therefore, the class has limited but appropriate functionality. For example, you can set the autoText property to have the control correct common misspellings. You can use the...

Debugging and Optimizing Layouts with the Hierarchy Viewer

The Android SDK ships with a host of tools that you can use to make your development life a lot easier. Because we are on the topic of user interface development, it makes sense for us to discuss the Hierarchy Viewer tool. This tool, shown in Figure 4-22, allows you to debug your user interfaces from a layout perspective. Figure 4-22. The layout view of the Hierarchy Viewer tool Figure 4-22. The layout view of the Hierarchy Viewer tool As shown in Figure 4-22, the Hierarchy Viewer shows the...

Understanding Content Providers

Android allows you to expose your data sources or data providers through a representational state transfer-like REST-like abstraction called a content provider. A SQLite database on an Android device is an example of a data source that you can encapsulate into a content provider. To retrieve data from a content provider or save data into a content provider, you will need to use a set of REST-like URIs. For example, if you were to retrieve a set of books from a content provider that is an...

Info Qpu

android text Start Animation Notice that the file location and the file name are embedded at the top of the XML file for your reference. This layout has two parts the first is the button named btn_animate to animate a view, and the second is the ListView, which is named list_view_id. Now that you have the layout for the activity, you can create the activity to show the view and set up the Start Animation button see Listing 6-15 . Listing 6-15. Code for the View-Animation Activity, Before...

glClear

You use the glClear method to erase the drawing surface. Using this method, you can reset not only the color, but also the depth and the type of stencils used. You specify which element to reset by the constant that you pass in GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, or GL_STENCIL_BUFFER_BIT. The color buffer is responsible for the pixels that are visible, so clearing it is equivalent to erasing the surface of any colors. The depth buffer refers to all the pixels that are visible in a 3D...

Caution The Android documentation seems to suggest that rounded corners are

To define one of these color rectangles, you define an XML element by the node name of drawable in any XML file in the res values subdirectory. Listing 3-14 shows a couple of color-drawable resource examples. Listing 3-14. XML Syntax for Defining Color-Drawable Resources lt resources gt lt drawable lt drawable lt drawable lt resources gt Listings 3-15 and 3-16 show how you can use a color-drawable resource in Java and XML, respectively. Listing 3-15. Using Color-Drawable Resources in Java Code...

Installing the ADT Plugin for Android 15 Development

The examples throughout the book have used Eclipse 3.4 Ganymede , and you'll want to ensure that you use this version when developing for Android 1.5. If you have installed an older version of the ADT plug-in 0.8 or lower , you'll need to uninstall that prior to installing the new ADT plug-in. To do that, launch the Eclipse IDE, select the Help menu item, and then choose the Software Updates option. In the Software Updates and Add-ons window, select the Installed Software tab. To remove the...

Obtaining a mapapi Key from Google

The first thing to understand about the map-api key is that you'll need two keys one for development with the emulator, and another for production on the device . The reason for this is that the certificate used to obtain the map-api key will differ between development and production as we discussed in the first part of this chapter . For example, during development, the ADT plug-in generates the .apk file and deploys it to the emulator. Because the .apk file must be signed with a certificate,...

Creating an Android Virtual Device

To run an application in the emulator requires a bit of setup with the new ADT plug-in. Specifically, before you can run an application in the emulator, you'll have to create at least one Android Virtual Device AVD . An AVD represents a device configuration. For example, you could have an AVD representing an Android device running version 1.5 of the SDK with a 32MB SD card. The idea is that you create AVDs you are going to support and then point the emulator to one of those AVDs when developing...

glViewport and Screen Size

glViewport is responsible for specifying the rectangular area on the screen onto which the viewing volume will be projected. This method takes four arguments to specify the rectangular box the x and y coordinates of the lower-left corner, followed by the width and height. Here is an example of specifying a view as the target for this projection glViewport 0, lower left x of the rectangle on the screen 0, lower left y of the rectangle on the screen width, width of the rectangle on the screen...

glDrawElements

Once you specify the series of points through glVertexPointer, you use the glDrawElements method to draw those points with one of the primitive shapes that OpenGL ES allows. Note that OpenGL is a state machine, meaning that it remembers the values set by one method when it invokes the next method in a cumulative manner. So you don't need to explicitly pass the points set by glVertexPointer to glDrawElements. glDrawElements will implicitly use those points. Listing 10-1 shows an example of this...

Understanding the LocationManager Service

The LocationManager service is one of the key services offered by the android.location package. This service provides two things a mechanism for you to obtain the device's geographical location, and a facility for you to be notified via an intent when the device enters a specified geographical location. In this section, you are going to learn how the LocationManager service works. To use the service, you must first obtain a reference to it. Listing 7-18 shows the usage pattern for the...

Understanding Android Menus

Whether you've worked with Swing in Java, with WPF Windows Presentation Foundation in Windows, or with any other UI framework, you've no doubt worked with menus. In addition to providing comprehensive support for menus, Android presents some new patterns such as XML menus and alternative menus. We will start this chapter by describing the basic classes involved in the Android menu framework. In the process, you will learn how to create menus and menu items, and how to respond to menu items. The...

glVertexpointer and Specifying Drawing Vertices

The glVertexPointer method is responsible for specifying an array of points to be drawn. Each point is specified in three dimensions, so each point will have three values x, y, and z. Here's how you can specify three points in an array This structure is a contiguous array of floats kept in a Java-based float array. Don't worry about typing or compiling this code anywhere yet our goal at this point is just to give you an idea of how these OpenGL ES methods work. We will give you the working...

MyContactsproviderjava

MyContactsProvider has the following responsibilities 1. Identify the incoming URI that looks like content com.ai.livefolders.contacts contacts. 2. Make an internal call to the Android-supplied contacts content provider identified by content contacts people . 3. Read every row from the cursor and map it back to a cursor like MatrixCursor with proper column names required by the live-folder framework. 4. Wrap the MatrixCursor in another cursor so that the requery on this wrapped cursor will make...

Implementing an AIDL Interface

In the previous section, we defined an AIDL file for a stock-quoter service and generated the binding file. Now we are going to provide an implementation of that service. To implement the service's interface, we need to write a class that extends android.app.Service and implements the IStockOuoteService interface. To expose the service to clients, we need to provide an implementation of the onBind method and add some configuration information to the AndroidManifest.xml file. Listing 8-12 shows...

Defining a Service Interface in AIDL

To demonstrate an example of a remote service, we are going to write a stock-quoter service. This service will provide a method that takes a ticker symbol and returns the stock value. To write a remote service in Android, the first step is to define the service definition in an AIDL file. Listing 8-10 shows the AIDL definition of IStockOuoteService. Listing 8-10. The AIDL Definition of the Stock-Quoter Service The IStockOuoteService accepts the stock-ticker symbol as a string and returns the...

Understanding AIDL Services

In the previous section, we showed you how to write an Android service that is consumed by the application that hosts the service. Now we are going to show you how to build a service that can be consumed by other processes via Remote Procedure Call RPC . As with many other RPC-based solutions, in Android you need an Interface Definition Language IDL to define the interface that will be exposed to clients. In the Android world, this IDL is called Android Interface Definition Language, or AIDL....

Taking Advantage of Android Source Code

During these early releases of Android, documentation is a bit wanting in places. When you run into that situation, it is worthwhile exploring Android source code to fill the gaps. The details of the Android source distribution are published at http source.android. com. The code was open sourced around October 2008 read the announcement at http source.android.com posts opensource . One of the Open Handset Alliance's goals was to make Android a free and fully customizable mobile platform. The...

Sending SMS Messages

To send a text message from your application, you will add the lt uses-permission gt permission to your manifest file and then use the android.telephony.gsm.SmsManager class see Listing 9-6 . Listing 9-6. Sending SMS Text Messages import android.telephony.gsm.SmsManager import android.view.View.OnClickListener public class TelephonyDemo extends Activity private static final String TAG TelephonyDemo Override protected void onCreate Bundle savedInstanceState super.onCreate savedInstanceState...

Associating a Drawing Surface with OpenGL ES Through the EGL Context

All of the Android SDK's samples use a view-related class called android.view.SurfaceHolder in order to draw using OpenGL ES. This class is closely related to android.view.SurfaceView, which is a variant of a regular view class that allows drawing from a separate thread. The documentation and samples don't make it clear whether you can use any other type of view for OpenGL drawing, so we'll stick to this android.view.SurfaceHolder object. Even if subsequent releases of Android were to allow...

Designing an Alert Dialog

We will begin our exploration with alert dialogs. Alert dialogs commonly contain simple messages about validating forms or debugging. Consider the following debug example that you often find in HTML pages indicate that formatting is not valid through an alert dialog showAlert What you have entered in fieldl doesn't match required format set focus to the field and continue You would likely program this dialog in JavaScript through the alert function, which displays a simple synchronous dialog...