Java Perspective

The Java Perspective is where you will spend most of your time while developing Android applications. The Java Perspective boasts a number of convenient views for assisting in the development process. The Package Explorer view allows us to see the Java projects in our Eclipse Workspace. Figure 2.2 shows the Package Explorer listing some of the sample projects for this book. The Java Perspective is where you will edit your Java source code. Every time your source file is saved, it is...

A3 Obtaining and installing the Android SDK

The Android SDK is available as a free download from a link on the Android home page, at SDK installation versions are available for multiple platforms, including Windows, Mac OS X (Intel x86 only), and Linux (i386). Select the latest version of the SDK for the desired platform. The Android SDK version shown in this appendix is marked 1.0_r1. The SDK will change from time to time as the Android team releases new versions. If you need to upgrade from one version to another, there will be an...

Android Project Wizard

The most straightforward manner to create an Android application is to utilize the services of the Android Project Wizard, which is part of the ADT plug-in. The wizard provides a simple means to define the Eclipse project name and location, the Activity name corresponding to the main UI class, as well as a name for the application. Of importance also is the Java package name under which the application is created. Once this application is created, it is easy to add new classes to the project....

Introducing Android

Android is the first open source mobile application platform that has the potential to make significant inroads in many markets. When examining Android there are a number of technical and market-related dimensions to consider. This first section introduces the platform and provides context to help you better understand Android and where it fits in the global cell phone scene. Android is the product of primarily Google, but more appropriately the Open Handset Alliance. Open Handset Alliance is...

Selling applications

A mobile platform is ultimately valuable only if there are applications to use and enjoy on that platform. To that end, the topic of buying and selling applications for Android is important and gives us an opportunity to highlight a key difference between Android and the iPhone. The Apple AppStore contains software titles for the iPhone. However, Apple's somewhat draconian grip on the iPhone software market requires that all applications be sold through its venue. This results in a challenging...

A1 Development environment requirements

In order to develop Android applications, your computing environment must satisfy the minimum requirements. Android development is a quick-paced topic, with changes coming about very rapidly, so it is a good idea to stay in tune with the latest developments from the Android development team at Google. The latest information regarding supported platforms and requirements for Android development tools may be found at html developmentrequirements. The development environment used for the sample...

PHP dispatcher code

The server-side dispatcher system is written in PHP and contains a number of files working together to create the application. Table 12.3 presents a brief synopsis of each source file to help you navigate the application should you choose to host a version of this application yourself. Form for entering new job information Used by Android application to submit signature Table 12.3 Server-side source code (continued) Table 12.3 Server-side source code (continued) Used to export list of jobs to a...

Location as an Edit Text View

Why are we using an EditText View for the location field in the ReviewCriteria Activity when Android includes technology that could be used to derive this value from the current physical location of the device (or allow the user to select it using a Map, rather than type it in) Good eye, but we are doing this intentionally here. We want this early example to be complete and nontrivial but not too complicated. You will learn more about using the location support Android provides and MapViews in...

Installing and running the application

In preparation to install and run the Hello Android application, let's take a tour of our build and testing environment. We need to identify four distinct environments tools and clearly understand them when building applications for Android Linux. The first environment to grasp is the big-picture architecture of the Android Emulator running essentially on top of Linux, as shown in figure 13.1. Figure 13.1 Android runs atop a Linux kernel. Figure 13.1 Android runs atop a Linux kernel. As...

Telephony background and terms

This basic information about telephony may not be new to experienced mobile developers (if that describes you, feel free to skip to the next section), but it's important to clarify terms and set out some background for those who are new to these concepts. First, telephony is a general term that refers to the details surrounding electronic voice communications over telephone networks. Our scope is, of course, the mobile telephone network that Android devices will participate in, specifically the...

Testing SMS

Data With Tiered Relationship

The emulator has a built-in set of tools for manipulating certain telephony behavior to simulate a variety of conditions, such as in and out of network coverage and placing phone calls. This section's example demonstrated another feature of the emulator, the receipt of an SMS message. To send an SMS message to the emulator, telnet to port 5554 (the port may vary on your system), which will connect to the emulator and issue the following command at the prompt sms send < sender's phone...

Testing Daytime Client

The first step in testing the Daytime Client is to ensure that the Daytime Server application is running, as described in section 13.3.4. Once you know the Daytime Server is running, you can run the Daytime Client. NOTE If you are unclear on how to build and run the Daytime Client, refer to chapter 2 for information on properly setting up the Android development environment in Eclipse. Figure 13.11 demonstrates the Daytime Client running, alongside a view of the Daytime Server. Note how the...

Working with Intent classes

Intent classes are the communications network of the applications on the Android platform. In many ways the Android architecture is similar to larger Service-Oriented Architecture (SOA) approaches in that each Activity makes a type of Intent call to get something done, without knowing exactly what the receiver of the Intent may be. In an ideal situation you don't care how a particular task gets performed rather, you care that it is done and is completed to your requirements. That way, you can...

Mapping applications to processes

Android applications each run in a single Linux process. Android relies on Linux for process management, and the application itself runs in an instance of the Dalvik virtual machine. The OS may need to unload, or even kill, an application from time to time to accommodate resource allocation demands. There is a hierarchy or sequence the system uses to select the victim of a resource shortage. In general, the rules are as follows Visible, running activities have top priority. Visible, nonrunning...

Listening in with broadcast receivers

Another way to use an Intent involves sending a broadcast to any interested receiver. There are many reasons an application may want to broadcast an event for example, when an incoming phone call or text message is received. In this section we will take a look at how events are broadcast and how they are captured using a BroadcastReceiver. Here we will continue working through the WeatherReporter sample application we began in the previous section. One of the most important parts of the...

Capturing media

Using your cell phone to take pictures, record memos, films short videos, and so on are all features now expected of any such device. In this section we are going to not only look at how to capture media from the microphone and camera but also write these files to the simulated SD card image we created previously. To get started let's examine how to use the Android Camera class to capture images and save them to a file. A very important feature of modern cell phones is their ability to take...

Else D Start Activityintent

New AlertDialog.Builder(this) setTitle(getResources() .getString(R.string.alert_label)) .setMessage(R.string.no_link_message) new OnClickListener() public void onClick(DialogInterface dialog, int argl) if ((this.location.getText() null) & & intent new Intent (Intent .ACTION_VIEW, Uri.parse(geo 0,0 q + this . location. getText (). toString ())) < 1-1 Set Intent for startActivity (intent) Q map menu item new AlertDialog.Builder(this) .setTitle(getResources()...

Communicating with a server socket

A server socket is a stream that you can read or write raw bytes to, at a specified IP address and port. This lets you deal with data and not worry about media types, packet sizes, and so on. This is yet another network abstraction intended to make the job of the programmer a bit easier. The philosophy that sockets take on, that everything should look like file I O to the developer, comes from the POSIX family of standards and has been adopted by most major operating systems in use today. We...

Application architecture and integration

Now that we know which entities are responsible for the relevant data elements, and in which direction they flow, let's look at how the data is stored and exchanged. We will be deep into code before too long, but for now we will discuss the available options and continue to examine things from a requirements perspective, building to a proposed architecture. At the home office, the dispatcher must manage data for multiple mobile workers. The best tool for this purpose is a relational database....

An overview of networking

A group of interconnected computers is a network. Over time, networking has grown from something that was once available only to governments and large organizations to the almost ubiquitous and truly amazing internet. Though the concept is simple allow computers to communicate networking does involve some advanced technology. We won't get into great detail here, though we will cover the core tenets as a background to the general networking we will do in the remainder of this chapter. A large...

Stacking up Android

The Android stack includes an impressive array of features for mobile applications. In fact, looking at the architecture alone, without the context of Android being a platform designed for mobile environments, it would be easy to confuse Android with a general computing environment. All of the major components of a computing platform are here and read like a Who's Who of the open source community. Here is a quick run-down of some of the prominent components of the Android stack A Linux kernel...

Command Line tools

The Android SDK ships with a collection of command-line tools, which are located in the tools subdirectory of your Android SDK installation. While Eclipse and the ADTs provide a great deal of control over our Android development environment, sometimes it is nice to exercise greater control, particularly when considering the power and convenience that scripting can bring to a development platform. We are going to explore two of the command-line tools found in the Android SDK. It is a good idea...

Android sample application code

The Android Application Wizard takes care of a number of important elements in the Android application structure, including the Java source files, the default resource files, and the AndroidManifest.xml file. Looking at the Package Explorer view in Eclipse we can see all of the elements of this application. Here's a quick description of the elements included in our sample application Figure 2.10 Using the Android Project Wizard, it is easy to create an empty Android application, ready for...

Booting Android development

This section jumps right into the fray of Android development to focus on an important component of the Android platform, then expands to take a broader view of how Android applications are constructed. An important and recurring theme of Android development is the Intent. An Intent in Android describes what you want to do. This may look like I want to look up a contact record, or Please launch this website, or Show the Order Confirmation Screen. Intents are important because they not only...

Exploring Activity lifecycle

Every process running on the Android platform is placed on a stack. When you use an Activity in the foreground, the system process that hosts that Activity is placed at the top of the stack, and the previous process (the one hosting whatever Activity was previously in the foreground) is moved down one notch. This is a key point to understand. Android tries to keep processes running as long as it can, but it can't keep every process running forever because, after all, system resources are...

Androids good Intentions

The power of Android's application framework lies in the way in which it brings a web mindset to mobile applications. This doesn't mean the platform has a powerful browser and is limited to clever JavaScript and server-side resources, but rather it goes to the core of how the Android platform itself works and how the user of the platform interacts with the mobile device. The power of the internet, should one be so bold to reduce it to a single statement, is that everything is just a click away....

Probing Androids foundation

Android is built on a Linux kernel and an advanced, optimized virtual machine for its Java applications. Both technologies are crucial to Android. The Linux kernel component of the Android stack promises agility and portability to take advantage of numerous hardware options for future Android-equipped phones. Android's Java environment is key it makes Android very accessible to programmers because of both the number of Java software developers and the rich environment that Java programming has...

In the market for an Android

Android promises to have something for everyone. Android looks to support a variety of hardware devices, not just high-end ones typically associated with expensive smart-phones. Of course, Android will run better on a more powerful device, particularly considering it is sporting a comprehensive set of computing features. The real question is how well Android can scale up and down to a variety of markets and gain market and mind share. This section provides conjecture on Android from the...

You say Intent I say Intent

The Intent class is used in similar sounding but very different scenarios. There are Intents used to assist in navigation from one activity to the next, such as the example given earlier of VIEWing a contact record. Activities are the targets of these kinds of Intents used with the startActivity or startActivityForResult methods. Services can be started by passing an Intent to the startService method. BroadcastReceivers receive Intents when responding to systemwide events such as the phone...

An Android application

This section presents a simple Android application demonstrating a single Activity, with one View. The Activity collects data, a street address to be specific, and creates an Intent to find this address. The Intent is ultimately dispatched to Google Maps. Figure 1.8 is a screen shot of the application running on the emulator. The name of the application is Where Do You Live. Figure 1.8 This Android application demonstrates a simple Activity and Intent. Figure 1.8 This Android application...

Listing 1310 Daytime application build script

Arm-none-linux-gnueabi-gcc -c daytime.c lt O Compile daytime.c arm-none-linux-gnueabi-gcc -c -o crto.o crt.S lt 1 Compile crt.S arm-none-linux-gnueabi-ld --entry _start --dynamic-linker system bin linker -nostdlib -rpath system lib -rpath-link android system lib -L android system lib -l c -l android_runtime -l sqlite -o daytime daytime.o C sof tware google lt path to android sdk gt tools adb Link the application push daytime data ch13 lt 1-1 g tools adb shell chmod 777 data ch13 daytime 'nstaH...

DDMS Perspective

The DDMS Perspective provides a dashboard-like view into the heart of a running Android device, or in our case, a running Android Emulator. Figure 2.5 shows the emulator running the Chapter2 sample application. We'll walk through the details of the application, including how to build the application and how to start it running in the Android Emulator, but first let's see what we can learn from the DDMS to continue the discussion of the tools available to us for Android development. The Devices...

Working with Content Provider classes

A ContentProvider is used in Android to share data between different applications. We have already discussed the fact that each application runs in its own process normally , and data and files stored there are not accessible by other applications by default. We have explained that you can make preferences and files available across application boundaries with the correct permissions and if each application knows the context path. Nevertheless, that is a limited solution for related...

Network speed

Network speed simulation is a key element of mobile software development. This feature is helpful because the actual user experience will vary during real-world use, and it is important that mobile applications degrade gracefully in the absence of a reliable network connection. The Android Emulator provides for a rich set of emulation tools for testing various network conditions and speeds. Table 2.1 lists the available network speed and latency conditions available in the Android Emulator....

Persisting data to a database

One nice convenience that the Android platform provides is the fact that a relational database is built in. SQLite doesn't have all of the features of larger client server database products, but it does cover just about anything you might need for local data storage, while being easy to deal with and quick. In this section we are going to cover working with the built-in SQLite database system, from creating and querying a database to upgrading and working with the sqlite3 tool that is available...

Using the filesystem

As you have seen, Android has a filesystem that is based on Linux and supports mode-based permissions. There are several ways you can access this filesystem. You can create and read files from within applications, you can access raw files that are included as resources, and you can work with specially compiled custom XML files. In this section we will take a tour of each approach. You can easily create files in Android and have them stored in the filesystem under the data path for the...

Field Service Activity part

The goal of the FieldService Activity is to put the functions the mobile worker requires directly in front of him and make sure they are easy to access. A good mobile application is often one that can be used with one hand, such as the five-way navigation buttons, or in some cases a thumb tapping on a button. In addition, if there is helpful information to display, you should not hide it. It is helpful for our mobile worker to know that he is configured to obtain jobs from a particular server....

Working with messaging SMS

SMS is a hugely popular and important means of communication for mobile devices. SMS is used to send simple text messages and small amounts of data. Android includes a built-in SMS application that allows users to view received SMS messages and send messages including replying to received messages . Along with the built-in user-facing support and the related ContentProvider for interacting with the built-in system, the SDK provides APIs for developers to be able to send and receive messages...

Grasping events

Events are used for changing the focus and for many other actions as well. We have already implemented several onClickListener methods for buttons in listing 3.2. Those OnClickListener instances were connected to button presses. The events they were indicating were Hey, somebody pressed me. This is exactly the same process that focus events go through when announcing or responding to OnFocus-Change events. Events have two halves the component raising the event and the component or components...

Exploring common views

Android provides a healthy set of View objects in the android.view package. These objects range from familiar constructs like the EditText, Spinner, and TextView that we have already seen in action to more specialized widgets such as AnalogClock, Gallery, DatePicker, TimePicker, and VideoView. For a quick glance at some of the more eye-catching views, check out the sample page in the Android documentation The class diagram in figure 3.4 provides a high-level snapshot of what the overall View...

This chapter covers

Using the network to retrieve and store data Every mobile provider supports voice and data networks of one or more types. The interesting part with an Android-enabled device is really the data network, along with the power to link the data available on the network to interesting applications. Those applications can then be built with the open Intent- and Service-based approach you learned about in previous chapters. That approach combines built-in or custom intents, such as fully capable web...

Listing 33 First half of the Review List Activity class showing a List View

Public class ReviewList extends ListActivity lt 1 Q Extend ListActivity private static final int MENU_CHANGE_CRITERIA Menu. FIRST 1 private static final int MENU_GET_NEXT_PAGE Menu. FIRST private static final int NUM_RESULTS_PER_PAGE 8 private ProgressDialog progressDialog Use ReviewAdapter private ReviewAdapter reviewAdapter lt 1-' private List lt Review gt reviews lt 1 Q Back Adapter with List private final Handler handler new Handler - , public void handleMessage final Message msg ' e...

Summary

The sample application is hosted on the internet and is free for you to test out with your own Android application, and of course the full source code is provided for the Android and server applications discussed in this chapter. Now that we have shown what can be accomplished when exercising a broad range of the Android SDK, the next chapter takes a decidedly different turn as we explore the underpinnings of Android a little deeper and look at building native C applications for the Android...

Using preferences

When moving from Activity to Activity in Android it is very handy to be able to save some global application state in a SharedPreferences object. Here we will discuss how you can set data into a preferences object and how you can later retrieve it. Also, we will discuss how to make preferences private to your application or accessible to other applications on the same device. 5.1.1 Working with SharedPreferences You access a SharedPreferences object through the Context you are working in. Many...

The static flag revisited

When an application is built with the -static flag, it is entirely self-contained, meaning that all of the routines it requires are linked directly into the application. This is not new information we have already discussed this. It has another important implication beyond just the size of the code it also means that using Android resident code libraries is a bigger challenge. Let's dig deeper to understand why. In order to do this, we have to look at the filesystem of Android Linux. System...

Introducing notifications

In the previous section we showed how simple it is to create a quick, unobtrusive message to let the user know an SMS message has arrived. In this next section we are going to look at how to create a persistent notification that not only shows up in the status bar but stays in a notification area until the user deletes it. To do that we need to use the class Notification since we want to do something more complex than Toast can offer us. A notification on Android can be many things, ranging...

Performing Inter Process Communication

Android Aidl Diagram

Communication between application components in different processes is made possible in Android by a specific IPC approach. This, again, is necessary because each application on the platform runs in its own process, and processes are intentionally separated from one another. In order to pass messages and objects between processes, you have to use the Android IPC path. To begin exploring this path we are first going to build a small, focused sample application to examine the means to generate a...

Listing 1111 A short Geocoder example

Public void onCreate Bundle savedInstanceState super.onCreate savedInstanceState this.setContentView R.layout.main this.input EditText this.findViewById R.id.input this.output TextView this.findViewById R.id.output this.button Button this.findViewById R.id. geocode_button this.isAddress CheckBox this .button.setOnClickListener new OnClickListener public void onClick final View v output.setText performGeocode input.getText .toString , isAddress.isChecked private String performGeocode String in,...

Multitasking with Handler and Message

The Handler is the Swiss army knife of messaging and scheduling operations for Android. This class allows you to queue tasks to be run on different threads and allows you schedule tasks using Message and Runnable objects. The Android platform monitors the responsiveness of applications and kills those that are considered nonresponsive. An Application Not Responding ANR event is defined as no response to a user input for five seconds. A user touches the screen, or presses a key, or the like, and...

Simulating your location within the emulator

For any location-aware application you will start by working with the provided SDK and the emulator. The first thing you will want to do within the emulator is set and update your current location. From there you will want to progress to supplying a range of locations and times to simulate movement over a geographic area. There are several ways you can accomplish these tasks for the emulator, either by using the DDMS tool or by using the command line within the shell. The fastest way to get...

Playing audio

Probably the most basic of needs for multimedia on a cell phone is the ability to play audio files, whether new ringtones, MP3s, or quick audio notes. Android's Media Player is easy to use. At a high level all you need to do to play back an MP3 file is follow these steps 1 Put the MP3 in the res raw directory in a project note that you can also use a URI to access files on the network or via the internet . 2 Create a new instance of the MediaPlayer and reference your MP3 by calling...

B22 Jarsigner

Once you have a private key, you can use it to sign your application files. Signing your files is done using the jarsigner tool. Before you can use the jarsigner tool, you need to export your project as an unsigned .apk archive. To export your project using the Eclipse ADT environment, right-click and select the Android Tools gt Export Unsigned Application Package option, as shown in figure B.1. Once you have an unsigned archive file, then you can use the jarsigner tool to sign it with your...

Animations

Kronos Glvertexpointer Tutorial

If a picture says a thousand words, then an animation must speak volumes. Android supports multiple methods of animations, including through XML, as you saw in chapter 3, or via Android's XML frame-by-frame animations using the Android Graphics API, or via Android's support for OpenGL ES. In this section we are going to create a very simple animation of a bouncing ball using Android's frame-by-frame animation. Android allows you to create simple animations by showing a set of images one after...

Introducing Toast

For our example we will create a simple Receiver class that listens for an SMS text message and when a message arrives briefly pops up a message, called a Toast, to the user with the content of the message. A Toast is a simple, nonpersistent message designed to alert the user of some occurring event. Toasts are a great way to let a user know that a call is coming in, an SMS or email has arrived, or some other event hasjust happened. To look at how we can use a Toast, let's create a simple...

Interacting with the phone

In your day-to-day development you will often want to interact with the phone. This interaction may be as simple as dialing outbound calls through built-in intents, or it may involve intercepting calls to modify them in some way. In this section we are going to cover these basic tasks, and we will examine some of the phone number utilities Android provides for you out of the box. One of the more common things you will do with the Android telephony support doesn't involve the telephony APIs...

Using Location Manager and Location Provider

When building location-aware applications on the Android platform, there are several key classes you will use very often. A LocationProvider provides location data using several metrics, and its data is accessed through a LocationManager. LocationManager, along with returning the available providers, also allows you to attach a LocationListener to be updated when the device location changes and or directly fire an Intent based on the proximity to a specified latitude and longitude. The...

Return trueIntent extra C

Intent new Intent this, ReviewCriteria.class startActivity intent return true return super.onMenuItemSelected featureld, item protected void onListItemClick ListView l, View v, D int position, long id lt 1-' RestaurantFinderApplication application RestaurantFinderApplication getApplication Intent intent new Intent Constants . INTENT_ACTION_VIEW_DETAIL getIntent .getIntExtra Constants . STARTFROM_EXTRA, 1 lt 1 startActivity intent Pass startFrom Get Application extra value object and set private...

Accessing telephony information

Android provides a very informative manager class that supplies information about many telephony-related details on the device. Using this class, TelephonyManager, you can access many of the GSM SIM properties we have already discussed, and you can obtain phone network state information and updates. Attaching an event listener to the phone, in the form of a PhoneStateListener, which is done via the manager, is how you can make your applications aware of when phone service is and is not...

Drawing graphics in Android

In this section we are going to be looking at Android's graphical capabilities as well as examples of how to make simple 2D shapes. We will be making use of the android.graphics package see android graphics package-summary.html , which provides all the low-level classes and tooling needed to create graphics. The graphics package supports such things as bitmaps which hold pixels , canvas what your draw calls draw on , primitives such as rectangles or text , and paint which you use to add color...

Working with maps

We have demonstrated the start of the MapViewActivity our Wind and Waves application will use in the previous sections. There we covered the supporting classes and the handling of registering to receive location updates. With that structure in place, we now will focus on the map details themselves. The MapViewActivity screen will look like the screen shot in figure 11.6, where several map Overlay classes are used on top of a MapView within a MapActivity. In order to use the com.google....

Understanding layout

One of the most significant aspects of creating your UI and designing your screens is understanding layout. In Android, screen layout is defined in terms of ViewGroup and LayoutParams objects. ViewGroup is a View that contains other views has children and also defines and provides access to the layout. On every screen all the views are placed in a hierarchical tree, so every element has children, and somewhere at the root is a ViewGroup. All the views on the screen support a host of attributes...