Sbd 1046 Pm

The user interface and layout of an activity We will refer to this layout hierarchy as we discuss the sample programs. For now, know that the application has one activity. The user interface for the activity is composed of three containers a container that contains a person's name, a container that contains the address, and an outer parent container for the child containers. The first example, Listing 4-1, demonstrates building the user interface entirely in code. To try this out,...

Programming 3D Graphics with OpenGL

I n this chapter, we will talk about working with the OpenGL graphics API on the Android Platform. Specifically, we'll break down the topic into three sections. First, we'll provide an overview of OpenGL, OpenGL for Embedded Systems (OpenGL ES), and some competing standards. Second, we will explain the theory behind OpenGL and cover some of the essential OpenGL ES APIs. In the third and final section, we will give you the necessary code to build a test harness that you can use to exercise the...

Understanding the Android Software Stack

So far we've covered Android's history and its optimization features including the Dalvik VM, and we've hinted at the Java programming stack available. In this section, we would like to cover the development aspect of Android. Figure 1-6 is a good place to start this discussion. Resources I Content Providers SQLite Figure 1-6. Detailed Android SDK software stack At the core of the Android Platform is Linux kernel version 2.6, responsible for device drivers, resource access, power management,...

Working with Raw Resources

Android also allows raw files in addition to raw XML files. These raw resources, placed in res raw, are arbitrary file resources such as audio, video, or text files that require localization or references through resource IDs. Unlike the raw XML files placed in res xml, these files are not compiled but moved to the application package as is. However, each file will have an identifier generated in R.java. If you were to place a text file at res raw test.txt, you would be able to read that file...

Generating a Self Signed Certificate Using the Keytool

The keytool utility manages a database of private keys and their corresponding X.509 certificates (a standard for digital certificates). This utility ships with the JRE and resides under the JRE bin directory. CHAPTER 7 EXPLORING SECURITY AND LOCATION-BASED SERVICES In this section, we'll show you how to generate a keystore with a single entry, which you'll later use to sign an Android .apk file. To generate a keystore entry, do the following 1. Create a folder to hold the keystore at c android...

Enumerating Key Android Resources

Now that we've been through the basics of resources, we'll enumerate some of the other key resources that Android supports, their XML representations, and the way they're used in Java code. (You can use this section as a quick reference as you write resource files for each resource.) To start with, take a quick glance at the types of resources and what they are used for (see Table 3-1). Arbitrary Raw res raw *.* Resources Arbitrary Raw assets *.* *.* Assets Represents color identifiers pointing...

OpenGL ES and Java ME

OpenGL ES, like OpenGL, is a C-based, flat API. Because the Android SDK is a Java-based programming API, you need a Java binding to OpenGL ES. Java ME has already defined this binding through JSR 239 Java Binding for the OpenGL ES API. JSR 239 itself is based on JSR 231, which is a Java binding for OpenGL 1.5. JSR 239 could have been strictly a subset of JSR 231, but that's not the case because it must accommodate some extensions to OpenGL ES that are not in OpenGL 1.5. You can find the...

Structure of Android MIME Types

Just as a web site returns a MIME type for a given URL, a content provider has an added responsibility to return the MIME type for a given URI. MIME types work in Android similar to how they work in HTTP. You ask a provider for the MIME type of a given URI that it supports, and the provider returns a two-part string identifying its MIME type according to the standard web MIME conventions. You can find the MIME-type standard here According to the MIME-type specification, a MIME type has two...

Using the Http Client for Http Get Requests

Here's the general pattern for using the HttpClient 1. Create an HttpClient (or get an existing reference). 2. Instantiate a new HTTP method, such as PostMethod or GetMethod. 3. Set HTTP parameter names values. 4. Execute the HTTP call using the HttpClient. Listing 8-1 shows how to execute an HTTP GET using the HttpClient. Note Because the code attempts to use the Internet, you will need to add android.permission. INTERNET to your manifest file when making HTTP calls using the HttpClient....

Building and Consuming Services

The Android Platform provides a complete software stack. This means you get an operating system and middleware, as well as working applications (such as a phone dialer). Alongside all of this, you have an SDK that you can use to write applications for the platform. Thus far, we've seen that we can build applications that directly interact with the user through a user interface. We have not, however, discussed background services or the possibilities of building components that run in the...

Consuming HTTP Services

Android applications and mobile applications in general are small apps with a lot of functionality. One of the ways that mobile apps deliver such rich functionality on such a small device is that they pull information from various sources. For example, the T-Mobile G1 comes with the Maps application, which provides seemingly sophisticated mapping functionality. We, however, know that the application is integrated with Google Maps and other services, which provide most of the sophistication....

Declaring and Using Permissions

Android defines a permission scheme meant to protect resources and features on the device. For example, applications, by default, cannot access the contacts list, make phone calls, and so on. To protect the user from malicious applications, Android requires applications to request permissions if they need to use a protected feature or resource. As you'll see shortly, permission requests go in the manifest file. At install time, the APK installer either grants or denies the requested permissions...

Exploring the Structure of an Android Application

Although the size and complexity of Android applications can vary greatly, their structures will be similar. Figure 2-7 shows the structure of the Hello World app you just built. - 0 pro.android + J HelloActivity.java + J R.java - & values 1 strings, xml Figure 2-7. The structure of the Hello World app Android applications have some artifacts that are required and some that are optional. Table 2-1 summarizes the elements of an Android application. (Note that Android 1.5 adds a few elements...

Analyzing the Notepad Application

Not only do you know how to create a new Android application and run it in the emulator, but you also have a feel for the artifacts of an Android application. Next, we are going to look at the Notepad application that ships with the Android SDK. Notepad's complexity falls between that of the Hello World app and a full-blown Android application, so analyzing its components will give you some realistic insight into Android development. Loading and Running the Notepad Application In this section,...

Video playback from the SD Card

Playing back video from the SD card requires little code, but it does require some prep work with regard to creating and configuring the emulator with the SD card. By default, the Android 1.1 emulator is not enabled with an SD card, so you first need to create an SD-card image and configure the emulator to use the SD card. After the card is created and the emulator is made aware of it, you can then use the Android tools within Eclipse to push the video file or any other file to the SD card....

The Frame Layout Layout Manager

The layout managers that we've discussed implement various layout strategies. In other words, each one has a specific way that it positions and orients its children on the screen. With these layout managers, you can have many controls on the screen at one time, each taking up a portion of the screen. Android also offers a layout manager that is mainly used to display a single item. This layout manager is called the FrameLayout layout manager. You mainly use this utility layout class to...

Understanding Local Services

Local services are services that are started via Context.startService . Once started, these types of services will continue to run until a client calls Context.stopService on the service or the service itself calls stopSelf . Note that when Context.startService is called, the system will instantiate the service and call the service's onStart method. Keep in mind that calling Context.startService after the service has been started that is, while it's running will not result in another instance...

Nature of Dialogs in Android

As we've mentioned, displaying dialogs in Android is an asynchronous process. Once a dialog is shown, the main thread that invoked the dialog returns and continues to process the rest of the code. This doesn't mean that the dialog isn't modal. The dialog is still modal. The mouse clicks apply only to the dialog, while the parent activity goes back to its message loop. On some windowing systems, modal dialogs behave a bit differently. The caller is blocked until the user provides a response...

Comparing Android and Java ME

As you have seen so far in this chapter, Android has taken a dedicated and focused approach to its mobile-platform efforts that goes beyond a simple JVM-based solution. The Android Platform comes with everything you need in a single package the OS, device drivers, core libraries, the JNI, the optimized Dalvik VM, and the Java development environment. Developers can be assured that when they develop new applications, all key libraries will be available on the device. Let us offer a brief...

Protected void applyTransformationfloat interpolatedTime Transformation t

Final Matrix matrix t.getMatrix matrix.setScale interpolatedTime, interpolatedTime The initialize method is a callback method that tells us about the dimensions of the view. This is also a place to initialize any animation parameters you might have. In this example, we have set the duration to be 2500 milliseconds 2.5 seconds . We have also specified that we want the animation effect to remain intact after the animation completes by setting FillAfter to true. Plus, we've indicated that the...

UI Development in Android

It's fun because the unattractive features in some other platforms are absent from Android. Swing, for example, has to support desktop applications as well as Java applets. Thus, the Java Foundation Classes JFC contains so much functionality that it's frustrating to use and difficult to navigate. JavaServer Faces JSF is another example. JSF, a common framework used to build web applications, is actually built on top of JavaServer Pages JSP and servlets. So you...

Working with Submenus

Let's take a look at Android's submenus now. Figure 5-1 points out the structural relationship of a SubMenu to a Menu and a MenuItem. A Menu object can have multiple SubMenu objects. Each SubMenu object is added to the Menu object through a call to the Menu.addSubMenu method see Listing 5-14 . You add menu items to a submenu the same way that you add menu items to a menu. This is because SubMenu is also derived from a Menu object. However, you cannot add additional submenus to a submenu....

The Relative Layout Layout Manager

Another interesting layout manager is the RelativeLayout. As the name suggests, this layout manager implements a policy where the controls in the container are laid out relative to either the container or another control in the container. Listing 4-32 and Figure 4-17 show an example. Listing 4-32. Using a RelativeLayout Layout Manager lt RelativeLayout lt TextView android text Username gt lt TextView android id id pwdLbl android text Password gt lt EditText android id id pwdText gt lt TextView...

Organizing Preferences

The preferences framework provides some support for you to organize your preferences into categories. If you have a lot of preferences, for example, you can build a view that shows highlevel categories of preferences. Users could then drill down into each category to view and manage preferences specific to that group. You can implement something like this in one of two ways. You can introduce nested PreferenceScreen elements within the root PreferenceScreen, or you can use PreferenceCategory...

Introducing the Input Method Framework

An exciting feature delivered with Android 1.5 is an input-method framework IMF implementation. IMF is actually a Java specification that decouples, for example, a text field from the mechanism that delivers text to the component. Example uses of an IMF include interpreters that translate speech into text, translators that convert text written with a pen device into regular text, interpreters that map characters from the Western alphabet table to characters in various east Asian languages such...

Understanding and Using Custom Permissions

Android allows you to define custom permissions with your application. For example, if you wanted to prevent certain users from starting one of the activities in your application, you could do that by defining a custom permission. To use custom permissions, you first declare them in your AndroidManifest.xml file. Once you've defined a permission, you can then refer to it as part of your component definition. We'll show you how this works. Let's create an application containing an activity that...

The Table Layout Layout Manager

The TableLayout layout manager is an extension of LinearLayout. This layout manager structures its child controls into rows and columns. Listing 4-28 shows an example. lt TableLayout lt TextView android text First Name gt lt EditText lt TextView android text Last Name gt lt EditText android text Obama gt To use a TableLayout, you create an instance of TableLayout and then place TableRow elements within it. TableRow elements then contain the controls of the table. The user interface for Listing...

Animating the List View

Now that you have the test harness ready see Listings 6-6 and 6-7 , you'll learn how to apply scale animation to this ListView. Take a look at how this scale animation is defined in an XML file see Listing 6-8 . Listing 6-8. Defining Scale Animation in an XML File android startOffset 100 gt These animation-definition files reside in the res anim subdirectory. Let's break down these XML attributes into plain English. The from and to scales point to the starting and ending magnification factors....

Calling the Service from a Client Application

When a client talks to a service, there must be a protocol or contract between the two. With Android, the contract is AIDL. So the first step in consuming a service is to take the service's AIDL file and copy it to your client project. When you copy the AIDL file to the client project, the AIDL compiler creates the same interface-definition file that was created when the service was implemented in the service-implementation project . This exposes to the client all of the methods, parameters,...

Exploring Audio Recording

The Android media framework supports recording audio and video. You record media using the android.media.MediaRecorder class. In this section, we'll show you how to build an application that records audio content and then plays the content back. We discuss video recording in Chapter 12. The user interface of the application is shown in Figure 9-6. Figure 9-6. The user interface of the audio-recorder example Figure 9-6. The user interface of the audio-recorder example As shown in Figure 9-6, the...

Using the Media Recorder Class for Video Capture

If you recall from Chapter 9, video recording was not possible with older versions of the SDK. With 1.5, you can begin to capture video using the media framework. Listing 12-1 demonstrates this. Note that we assume that you have read Chapter 9 and understand how to use the APIs from the media framework. If you have not read Chapter 9, you should do so before continuing with this section. Also realize that Listing 12-1 will not work on an emulator because video recording requires a...

Creating a Menu

In the Android SDK, you don't need to create a menu object from scratch. Because an activity is associated with a single menu, Android creates this single menu and passes it to the onCreateOptionsMenu callback method. As the name of the method indicates, menus in Android are also known as options menus. This method allows you to populate the menu with a set of menu items see Listing 5-1 . Listing 5-1. Signature for the onCreateOptionsMenu Method Override public boolean onCreateOptionsMenu Menu...

Video Playback from a Web Server

As we said, playing video requires more effort than playing audio. To take some of the pain away, Android provides a specialized view control called android.widget.VideoView that encapsulates creating and initializing the MediaPlayer. To play video, you create a VideoView widget and set that as the content of the UI. You then set the path or URI of the video and fire the start method. Listing 9-4 demonstrates video playback in Android. Listing 9-4. Playing a Video Using the Media APIs lt xml...

Creating and Using the OpenGL Test Harness

The OpenGL test harness that you'll develop in this section will serve as an excellent tool to learn and experiment with OpenGL programming. It will hide the OpenGL ES and Android-specific initializations through the designed encapsulation. These processes will be encapsulated 2. Initializing the EGL context with a SurfaceView 3. Dealing with threading issues when working with the SurfaceView 4. Setting up the camera to provide a standard set of dimensions for your drawing We'll base this test...

Creating a Simple Service

To build a service, you extend the abstract class android.app.Service and put a service-configuration entry in your application's manifest file. Listing 8-7 shows an example. Listing 8-7. A Simple Android Service Definition public class TestServicel extends Service private static final String TAG TestServicel public void onCreate Log.d TAG, onCreate super.onCreate public IBinder onBind Intent intent Log.d TAG, onBind return null service definition entry must go in the AndroidManifest.xml file....

OpenGL Animation Example

You can easily accommodate OpenGL animation in the new Android release by changing the rendering mode on the GLSurfaceView object see Listing 13-7 . Listing 13-7. Specifying Continuous-Rendering Mode get a GLSurfaceView GLSurfaceView openGLView Set the mode to continuous draw mode Note that we're showing you how to change the rendering mode here because we had specified RENDERMODE_WHEN_DIRTY in the previous section. As we mentioned, RENDERMODE_ CONTINUOUSLY is in fact the default setting, so...

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

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 Radio Button 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 Alert Dialog 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 Media Store 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...

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

Geocoding with Android

Android Geocoder

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

Text View

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 setData Source 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 Map View and Map Activity

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

Dialog FinishedCall Back

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

Edit Text

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

Info

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

Caution The Android documentation seems to suggest that rounded corners are possible At least in releases 10 11 and 15

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

GlDraw Elements

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

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