52862.fb2 Beginning Android - читать онлайн бесплатно полную версию книги . Страница 10

Beginning Android - читать онлайн бесплатно полную версию книги . Страница 10

APPENDIX

Introducing Android 1.5

Android is a continuously changing product. In fact, while this book was being put into production Google and the Open Handset Alliance released Android 1.5.

This was great for you, the developer, because Android 1.5 adds in quite a bit more to the product.

On the other hand, the timing left a bit to be desired in terms of getting this book into print. The vast majority of what you have read so far is accurate for Android 1.1 and Android 1.5. This Appendix will point out the exceptions — the places where Android changed and so the advice for Android 1.1 is no longer correct. Those changes are few in number, so the bulk of this Appendix is spent covering what is new and how, in basic terms, you can make use of the new material as a developer. This material is nowhere near the depth that you will find in the rest of the book, because Android 1.5 has been available for only a few weeks, and it will take months to write up everything that is new and exciting.

Getting Started, Virtually

Android 1.5 introduced the Android Virtual Device (AVD) system. This allows you to have multiple Android emulator images available, targeting different device profiles. Each image can vary in terms of Android API version (e.g., 1.1 versus 1.5), available add-ons (e.g., whether or not Google Maps are included), and hardware capabilities (e.g., does it have a touch screen?).

To create an AVD, you must first choose a “target”. Targets represent a combination of an API version and a set of available add-ons. You can find out the available targets for your environment by executing the following command:

android list targets

For example, at the time of this writing, three targets are available:

• 1, indicating the Android 1.1 SDK with no add-ons

• 2, indicating the Android 1.5 SDK with no add-ons

• 3, indicating the Android 1.5 SDK with the Google Maps add-on

Then, once you have a target in mind, to create the AVD itself, execute the following command:

android create avd -n ... -t ...

The first ellipsis indicates where you specify your own name for this AVD; the second ellipsis is where you fill in the target you wish from the available targets in your environment.

If you choose a target that represents a “standard system image” (i.e., no add-ons), you will be prompted to optionally configure the hardware profile. If you go through that process, you will be able to determine how much RAM is in your emulated device, whether or not it has a touchscreen, etc.

Creation, Yes. Myth, No.

With the new AVD system comes a new way of creating and updating projects for use with the Ant build system.

To create a new project, run android create project. This will require a few additional parameters, notably:

• -k to supply the package name to use with your application (e.g., -k com.commonsware.android.sample)

• -n to supply the name of the project, which will determine the name of the APK file (e.g., -n MyProject)

• -a to supply the name of the activity class (e.g., -a MyMainActivity)

• -t to supply the target ID for use with this project, following the same target system used when creating AVDs, described in the preceding section “Getting Started, Virtually” (e.g., -t 3)

• -p to indicate where the project files should be generated (e.g., -n MyProject)

To update an existing project, run android update project. This will replace your build.xml file and do a few other odds and ends to convert a project to be built using the Android 1.5 build system. As with android create project, you will want to provide a few additional parameters on the command, including:

• -t to supply the target ID for use with this project, following the same target system used when creating AVDs, described in the preceding section “Getting Started, Virtually” (e.g., -t 3)

• -p to indicate where the project files should be generated (e.g., -n MyProject)

Make Your Demands Heard

In addition to using the target ID system to indicate what level of device your project is targeting, you can use a new AndroidManifest.xml element to specify hardware that is required for your application to run properly.

You can add one or more <uses-configuration> elements inside the <manifest> element. Each <uses-configuration> element specifies one valid configuration of hardware that your application will work with.

At the present time, there are five possible hardware requirements you can specify this way:

• android:reqFiveWayNav to indicate you need a 5-way navigation pointing device of some form (e.g., android:reqFiveWayNav="true")

• android:reqNavigation to restrict the 5-way navigation pointing device to a specific type (e.g., android:reqNavigation="trackball")

• android:reqHardKeyboard to specify if a hardware (physical) keyboard is required (e.g., android:reqHardKeyboard="true")

• android:reqKeyboardType, probably used in conjunction with android:reqHardKeyboard, to indicate a specific type of hardware keyboard that is required (e.g., android:reqKeyboardType="qwerty")

• android:reqTouchScreen to indicate what type of touchscreen is required, if any (e.g., android:reqTouchScreen="finger")

Add and Subtract

Since the Android M5 SDK in the summer of 2008, Google Maps has been available to application developers willing to agree to the terms and conditions. However, since Google Maps is not part of the open source Android project, there was always the possibility that some Android devices would not have Google Maps on them. For example, anyone porting Android via the open source project to existing hardware on a “homebrew” basis would unlikely be in a position to license Google Maps.

To accommodate this and similar scenarios with other possible technology, Android 1.5 has introduced a more formal add-on mechanism. You can see this with the target ID system, whereby some targets have Google Maps and others do not. If a device manufacturer decides to add some APIs to their devices that are unique to them, presumably they could use this same add-on system to help developers target their devices. This also opens up the possibility for other platform-level optional components, particularly ones that might need to be licensed, such as the oft-rumored Adobe Flash add-on.

Slide and Scroll

Android 1.5 introduces some new widgets, notably SlidingDrawer and HorizontalScrollView.

SlidingDrawer introduces a container akin to the one on the home screen used to hold the application icons. You control the image to use for the drawer “handle” and the contents to go in the drawer. You can also control the orientation, to determine if the drawer opens from the bottom or the side. Then, you can add listeners to monitor the state of the drawer, or toggle the state yourself, if desired.

As the name suggests, HorizontalScrollView works just like the original ScrollView except that it scrolls horizontally, not vertically.

Squeezably Soft

With the May 2009 debut of the HTC Magic, we now have Android phones lacking hardware keyboards. This makes text entry rather difficult… except that Android 1.5 added in support for soft keyboards. Soft keyboards also help for internationalization, as the user is not limited to the particulars of whatever hardware keyboard their device may actually have.

Soft keyboards take effect automatically, for basic functionality. The EditText widgets in your layout will cause the soft keyboard to spring up, assuming the device either does not have a QWERTY keyboard (e.g., HTC Magic) or is being held with the keyboard closed (e.g., T-Mobile G1 in portrait mode) as seen in Figure A-1.

Figure A-1. Android 1.5’s Input Method Editor (a.k.a., soft keyboard)

You can tailor the behavior of the soft keyboard in your layouts or via Java code. For example, in the screenshot shown previously, you will see a “Next” button in the lower-right corner. By default, Android will take a guess as what to use this “action button” for — in this case, it moves you to the next field. You can add attributes to your layout to control what the caption is for this button, and what actually occurs when the action button is tapped. So, for example, if you are allowing people to enter a URL to visit in a Web browser, you might rename the action button to “Go” and have it launch the Browser application upon the typed-in URL.

You can also provide light control over what sort of keyboard is displayed by indicating what sort of text entry is supposed to occur in the EditText. For example, you can indicate that the android:inputType is textEmailAddress, which will ensure an @ key is available without having to use a soft shift key.

You can also control what happens to your activity layout when the soft keyboard is displayed. Your activity can either scroll out of the way to support the keyboard, or it can be resized to accommodate the keyboard, or have the keyboard appear full-screen, eclipsing your activity until the text entry is complete. Android will attempt to determine the best answer automatically, but via the android:windowSoftInputMode on your <activity> element in your manifest, you can override the default behavior.

This Input Method Framework (IMF) is extensible, should you wish to create your own customized soft keyboard (a.k.a., input method editor, or IME) for use in your application or by other applications. A sample IME is provided with the SDK to serve as a basis for your own custom keyboards.

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 add in a couple of more app widgets (e.g., media player, picture frame), but users can add and remove app widgets, and developers can create their own (see Figure A-2).

Figure A-2. Some stock Android 1.5 app widgets

App widgets are built not using ordinary layouts, but rather with a layout subset known as RemoteViews. You cannot use arbitrary widgets with RemoteViews, though it supports many common ones. The term “remote views” comes from the fact that while the UI is defined by your application, the UI (in the form of the “app widget”) runs in the context of another application, in this case the home screen.

Implementing an app widget involves creating some XML metadata, associating that metadata with a <receiver> element in your manifest, and implementing that receiver as an AppWidgetProvider. Most likely in conjunction with a service that will handle any time-consuming work (e.g., network lookups), your provider will create and push out RemoteViews when requested by the home screen. Note that app widgets are designed for infrequent update, since frequent polling for new widget contents can rapidly drain the device battery.

Live folders are, in essence, a simplified home-screen-launched look into the contents published by a ContentProvider. In the screenshot shown previously, you see a “Phones” icon. Tapping that brings up a dialog over the home screen containing a list of all contacts containing phone numbers as you can see in Figure A-3.

Figure A-3. A Live Folder in Android 1.5

Tapping an individual contact, of course, brings up the detail screen for that contact.

To create your own live folders for your users to offer, you can add an intent filter watching for a CREATE_LIVE_FOLDER Intent on an activity in your application. That activity, in turn, simply calls setResult() with another Intent object, this one describing the live folder, such as its icon, name, and display mode (e.g., LiveFolders.DISPLAY_MODE_LIST). This Intent also contains the Uri pointing to the ContentProvider whose information you are trying to display. That ContentProvider should be updated to recognize the live folder Uri and, on query(), return an ID, title, and description of each piece of content in the provider (or a subset if appropriate). Android will take care of the rest, in terms of formatting the data in the live folder convention (large font title, small font description), pouring the query results into a list, etc.

Tying Up Loose Threads

A common pattern in Android is to perform some work on a background thread, then update something on the UI thread when the background work is complete. A simple way to handle this is to fork a background thread and use a Handler or runOnUiThread() to accomplish the UI thread work. However, the danger here is in forking too many threads — the user might do something that causes you to fork many threads in short order, bogging down the device at best. And while there are classes that can help you manage a work pool (e.g., LinkedBlockingQueue), their use can be mildly tedious.

Enter AsyncTask.

AsyncTask manages a work queue with a thread pool, so you do not need to implement that yourself. Moreover, all of the communication between foreground and background threads are handled for you. All you need to do is override a few methods to describe what you want done in the background or in the foreground.

To create an AsyncTask, simply extend one anonymously, like you might do to create a Runnable. You can then override whatever methods you need to for the pattern you want:

• Override onPreExecute() to specify something that should be done on the UI thread when the task is started

• Override doInBackground() to indicate the work that should be done in the background thread

• Override onProgressUpdate() to update your progress on the UI thread when doInBackground() calls publishProgress() (e.g., update a ProgressBar)

• Override onPostExecute() to do whatever work needs to be done on the UI thread after the background work is complete

Using your custom AsyncTask is then a matter of calling execute() on one of its instances, such as one might call run() on a Runnable.

Now, the Rest of the Story

Of course, there are many, many more things added to Android 1.5 beyond what is covered earlier. Here is a quick recap of other capabilities you will be able to take advantage of in Android 1.5.

Speech Recognition

Android 1.1 debuted Google Voice Search, where you could tap on a microphone icon text to the search field on the home screen, speak your search request, and have the search conducted on what you said.

Android 1.5 opens this up to be available to all applications. You can start an activity using an Intent using the RecognizerIntent.ACTION_RECOGNIZE_SPEECH action and have the converted text supplied to you in response via onActivityResult().

IntentService

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. Android will also automatically stop the service when the work queue becomes empty, to help minimize the memory footprint of your application.

Audio Playback Options

The SoundPool class, largely undocumented in Android 1.1, is now ready for widespread use in Android 1.5. The SoundPool is designed to play back multiple overlapping sounds, particularly useful for games. Moreover, you can specify priorities for these audio streams and a maximum number of streams, so your application can simply play back clips as needed (e.g., based on game events), and Android will ensure the maximum number of streams is not exceeded. That way, you can minimize the amount of CPU power audio playback requires.

Android 1.5 also offers AudioTrack, whereby the device can play back audio that your code converts, perhaps from a streaming source, into PCM data. So, for example, should you want to implement a Voice-Over-IP (VOIP) application, you might use AudioTrack to handle playback of the audio coming off of, say, the SIP connection.

Android 1.5 also introduces the JetPlayer, designed to play back JET interactive music filesJET interactive music files.

Media Recording

Android 1.1 offered a MediaRecorder class, but it would only record audio. Now, with Android 1.5, you can record video as well. You control the frame rate and size, along with the encoding (e.g., H.264) and output format (e.g., MP4). Android will then, on demand, record video off of the device’s camera to a file you specify.