Manifest Destiny

Finally, you need to add the service to your AndroidManifest.xml file, for it to be recognized as an available service for use. That is simply a matter of adding a service element as a child of the application element, providing android name to reference your service class. For example, here is the AndroidManifest.xml file for WeatherPlus < xml version 1.0 encoding utf-8 > < manifest < uses-permission > < uses-permission COARSE LOCATION > < uses-permission FINE LOCATION > <...

Yet More Inflation

You saw in Chapter 9 that you can describe Views via XML files and inflate them into actual View objects at runtime. Android also allows you to describe menus via XML files and inflate them when a menu is called for. This helps you keep your menu structure separate from the implementation of menu-handling logic, and it provides easier ways to develop menu-authoring tools. Menu XML goes in res menu in your project tree, alongside the other types of resources that your project might employ. As...

DIY Rotation

Even this, though, may still be too intrusive to your application. Suppose, for example, you are creating a real-time game, such as a first-person shooter. The hiccup your users experience as your activity is destroyed and re-created might be enough to get them shot, which they may not appreciate. While this would be less of an issue on the T-Mobile G1, since a rotation requires sliding open the keyboard and therefore is unlikely to be done mid-game, other devices might rotate based solely upon...

Fields Now with 35 Less Typing

The AutoCompleteTextView is sort of a hybrid between the EditText (field) and the Spinner. With auto-completion, as the user types, the text is treated as a prefix filter, comparing the entered text as a prefix against a list of candidates. Matches are shown in a selection list that, like with Spinner, folds down from the field. The user can either type out an entry (e.g., something not in the list) or choose an entry from the list to be the value of the field. AutoCompleteTextView subclasses...

Quick SQLite Primer

SQLite, as the name suggests, uses a dialect of SQL for queries (SELECT), data manipulation (INSERT, et al), and data definition (CREATE TABLE, et al). SQLite has a few places where it deviates from the SQL-92 standard, no different than most SQL databases. The good news is that SQLite is so space-efficient that the Android runtime can include all of SQLite, not some arbitrary subset to trim it down to size. The biggest difference from other SQL databases you will encounter is probably the data...

Scrollwork

Phone screens tend to be small, which requires developers to use some tricks to present a lot of information in the limited available space. One trick for doing this is to use scrolling, so only part of the information is visible at one time, and the rest is available via scrolling up or down. ScrollView is a container that provides scrolling for its contents. You can take a layout that might be too big for some screens, wrap it in a ScrollView, and still use your existing layout logic. It just...

The Kind of Pop Ups You Like

Of course, not all preferences are checkboxes and ringtones. For others, like entry fields and lists, Android uses pop-up dialogs. Users do not enter their preference directly in the preference UI activity, but rather tap on a preference, fill in a value, and click OK to commit the change. Structurally, in the preference XML, fields and lists are not significantly different from other preference types, as seen in this preference XML from the Prefs Dialogs sample project available at http...

Tabbed Browsing Sort Of

One of the main features of the modern desktop Web browser is tabbed browsing, where a single browser window can show several pages split across a series of tabs. On a mobile device this may not make a lot of sense, given that you lose screen real estate for the tabs themselves. In this book, however, we do not let little things like sensibility stop us, so let me demonstrate a tabbed browser, using TabActivity and Intents. As you may recall from Chapter 10, a tab can have either a View or an...

Grid Your Lions or Something Like That

As the name suggests, GridView gives you a two-dimensional grid of items to choose from. You have moderate control over the number and size of the columns the number of rows is dynamically determined based on the number of items the supplied adapter says are available for viewing. There are a few properties which, when combined, determine the number of columns and their sizes android numColumns spells out how many columns there are, or, if you supply a value of auto fit, Android will compute...

Wiring It Together

The Java code needs to tell the TabHost what views represent the tab contents and what the tab buttons should look like. This is all wrapped up in TabSpec objects. You get a TabSpec instance from the host via newTabSpec , fill it out, then add it to the host in the proper sequence. The two key methods on TabSpec are setContent , where you indicate what goes in the tab content for this tab, typically the android id of the view you want shown when this tab is selected setIndicator , where you...

Screenshots

To take a screenshot of the Android emulator or device, simply press lt Ctrl gt - lt S gt or choose Device gt Screen capture from the main menu. This will bring up a dialog box containing an image of the current screen shown in Figure 37-11. From here, you can click Save to save the image as a PNG file somewhere on your development machine, Refresh to update the image based on the current state of the emulator or device, or Done to close the dialog.

Love the One Youre With

Android natively knows three fonts, by the shorthand names of sans, serif', and monospace. These fonts are actually the Droid series of fonts, created for the Open Handset Alliance by Ascender.1 For those fonts, you can just reference them in your layout XML, if you so choose. The following layout from the Fonts FontSampler sample project shows example code, and can also be found in the Source Code area at http apress.com lt xml version 1.0 encoding utf-8 gt lt TableLayout android layout width...

OK So What Does It Look Like

Here is the Button from the previous chapter's sample application, converted into an XML layout file, found in the Layouts NowRedux sample project. This code sample along with all others in this chapter can be found in the Source Code area of http apress.com. lt xml version 1.0 encoding utf-8 gt lt Button android id id button android text android layout width fill parent android layout height fill parent gt The class name of the widget Button forms the name of the XML element. Since Button is...

Adapting to the Circumstances

Now that we have a Cursor via managedQuery , we have access to the query results and can do whatever we want with them. You might, for example, manually extract data from the Cursor to populate widgets or other objects. However, if the goal of the query was to return a list from which the user should choose an item, you probably should consider using SimpleCursorAdapter. This class bridges between the Cursor and a selection widget, such as a ListView or Spinner. Pour the Cursor into a...

Letting Users Have Their

Given that you have set up the preference XML, you can use a nearly built-in activity for allowing your users to set their preferences. The activity is nearly built-in because you merely need to subclass it and point it to your preference XML, plus hook the activity into the rest of your application. So, for example, here is the EditPreferences activity of the Prefs Simple project available on the Apress Web site package com.commonsware.android.prefs import public class EditPreferences extends...

Hunting Season

There are two types of search in Android local and global. Local search searches within the current application global search searches the Web via Google's search engine. You can initiate either type of search in a variety of ways, including the following You can call onSearchRequested from a button or menu choice, which will initiate a local search unless you override this method in your activity . You can directly call startSearch to initiate a local or global search, including optionally...

And Checking It Twice

The rating list in the previous section works, but implementing it is very tedious. Worse, much of that tedium would not be reusable except in very limited circumstances. We can do better. What we'd really like is to be able to create a layout like this lt xml version 1.0 encoding utf-8 gt lt LinearLayout android layout width fill parent android layout height fill parent gt lt TextView android id id selection android layout width fill parent android layout height wrap content gt android id...

Making a List

Lists with pretty icons next to them are all fine and well. But can we create ListView widgets whose rows contain interactive child widgets instead of just passive widgets like TextView and ImageView For example, could we combine the RatingBar with text in order to allow people to scroll a list of, say, songs and rate them right inside the list The good news is that interactive widgets in rows work just fine. The bad news is that it is a little tricky, specifically when it comes to taking...

Intent Service

A common pattern, particularly when using AlarmManager for scheduling periodic background work, is to have a service that implements onStart and forks a background thread to do the desired work. This runs the risk of forking too many threads, though, and managing your own work queue and thread pool can be annoying. The IntentService class wraps that pattern up for you. All you do is implement onHandleIntent , and Android will process all inbound Intents via a work queue on a background thread....

Delightful Dalvik Debugging Detailed Demoed

Another tool in the Android developer's arsenal is the Dalvik Debug Monitor Service DDMS . This is a Swiss Army knife, allowing you to do everything from browse log files, update the GPS location provided by emulator, simulate incoming calls and messages, and browse the on-emulator storage to push and pull files. DDMS has a wide range of uses, so this section will not try to cover them all, rather it will cover the most useful at the time of writing. To launch DDMS, run the ddms program inside...

Sprucing Up Your Home

Android 1.5 lets you do more with the built-in home screen application, notably by adding app widgets and live folders. As an application developer, you can choose to offer app widgets and or live folders from your own applications for users to add to their home screens. App widgets are simply user interface elements added to the home screen. Previous Android editions had some of these the analog clock, the Google search bar , but they were fixed in type and number. Now, not only does Android...

Data Data Everywhere

If you are used to developing for other databases, you are also probably used to having tools to inspect and manipulate the contents of the database, beyond merely the database's API. With Android's emulator, you have two main options for this. First, the emulator is supposed to bundle in the sqlite3 console program and makes it available from the adb shell command. Once you are in the emulator's shell, just execute sqlite3, providing it the path to your database file. Your database file can be...

Following the Script

Unlike other mobile-device operating systems, Android has no restrictions on what you can run on it, so long as you can do it in Java using the Dalvik VM. This includes incorporating your own scripting language into your application, something that is expressly prohibited on some other devices. One possible Java scripting language is BeanShell.1 BeanShell gives you Java-compatible syntax with implicit typing and no compilation required. So, to add BeanShell scripting, you need to put the...

My Myself and MyLocation Overlay

Android has a built-in overlay to handle two common scenarios Showing where you are on the map, based on GPS or other location-providing logic Showing where you are pointed, based on the built-in compass sensor, where available All you need to do is create a MyLocationOverlay instance, add it to your MapView's list of overlays, and enable and disable the desired features at appropriate times. The at appropriate times notion is for maximizing battery life. There is no sense in updating locations...

Flipping Them

Sometimes, you want the overall effect of tabs only some Views visible at a time , but you do not want the actual UI implementation of tabs. Maybe the tabs take up too much screen space. Maybe you want to switch between perspectives based on a gesture or a device shake. Or maybe you just like being different. The good news is that the guts of the view-flipping logic from tabs can be found in the ViewFlipper container, which can be used in other ways than the traditional tab. ViewFlipper...

Readin n Writin

Reading and writing your own, application-specific data files is nearly identical to what you might do in a desktop Java application. The key is to use openFileInput and openFileOutput on your Activity or other Context to get an InputStream and OutputStream, respectively. From that point forward, the process is not much different from using regular Java I O logic Wrap those streams as needed, such as using an InputStreamReader or OutputStreamWriter for text-based I O. Use close to release the...