Maps Geocoding and LocationBased Services
gt Forward and reverse geocoding gt Creating interactive maps with Map Views and Map Activities gt Creating and adding Overlays to maps gt Finding your location with location-based services One of the defining features of mobile phones is their portability, so it's not surprising that some of the most enticing Android features are the services that let you find, contextualize, and map physical locations. You can create map-based Activities using Google Maps as a user interface element. You...
Explicitly Starting New Activities
You learned in Chapter 2 that applications consist of a number of interrelated screens Activities that must be included in the application manifest. To connect them you may want to explicitly specify an Activity to open. To explicitly select an Activity class to start, create a new Intent, specifying the current application Context and Activity class to launch. Pass this Intent in to startActivity as shown in Listing 5-1. LISTING 5-1 Explicitly starting an Activity Available for download on...
Reading Network Details
When you are connected to a network, you can use the Telephony Manager to read the mobile country and network code MCC MNC , the country ISO code, and the type of network you're connected to. These commands will only work when you are connected to a mobile network, and can be unreliable if it is a CDMA network. Use the getPhoneType method as described above to determine which network type you are connected to. Listing 12-5 shows how to extract the network details, as well as showing a list of...
Supplying Anonymous Actions to Applications
To use this mechanism to make your Activity's actions available anonymously for existing applications, publish them using intent-filter tags within their manifest nodes. The Intent Filter describes the action it performs and the data upon which it can be performed. The latter will be used during the Intent resolution process to determine when this action should be available. The category tag must be either ALTERNATIVE or SELECTED_ALTERNATIVE or both. The text used for the Menu Items is...
Native Android Broadcast Actions
Android broadcasts Intents for many of the system Services. You can use these messages to add functionality to your own projects based on system events such as time-zone changes, data-connection status, incoming SMS messages, or phone calls. The following list introduces some of the native actions exposed as constants in the Intent class these actions are used primarily to track device status changes. gt action_boot_completed Fired once when the device has completed its startup sequence. An...
Ongoing and Insistent Notifications
You can configure Notifications as ongoing and or insistent by setting the flag_insistent and FLAG_ONGOING_EVENT flags. Notifications flagged as ongoing, as in the following snippet, are used to represent events that are currently in progress such as a download in progress or music playing in the background . An ongoing Notification is a requirement for a foreground Service, as described earlier in this chapter. notification.flags notification.flags Notification.FLAG_ONGOING_EVENT Ongoing...
Android Database Design Considerations
There are several considerations specific to Android that you should keep in mind when designing your database. gt Files such as bitmaps or audio files are not usually stored within database tables. Use a string to store a path to the file, preferably a fully qualified URI. gt While not strictly a requirement, it's strongly recommended that all tables include an auto-increment key field as a unique index field for each row. If you plan to share your table using a Content Provider, a unique ID...
Broadcasting Sticky and Ordered Intents
When broadcasting an Intent using sendBroadcast, your Intent will be received by all registered Broadcast Receivers, but you cannot control the order and they cannot propagate results. In circumstances where the order in which the Broadcast Receivers receive the Intent is important, or where you require the Receivers to be able to affect the Intent being broadcast, you can use the sendOrderedBroadcast method. Using this method, your Intent will be delivered to all registered Receivers in order...
Available for
download on RemoteViews views new RemoteViews context.getPackageName , To use Remote Views on widgets, call the static getinstance method to return an instance of the App Widget Manager and use it to find identifiers for each instance of a particular widget class, as in this continuation of Listing 10-5 AppWidgetManager appWidgetManager AppWidgetManager.getlnstance context Retrieve the identifiers for each instance of your chosen widget. ComponentName thisWidget new ComponentName context,...
Monitoring Data Connectivity and Activity
As well as voice and service details, you can also use a Phone State Listener to monitor changes in mobile data connectivity and mobile data transfer. The Phone State Listener includes two event handlers for monitoring the device data connection. Override onDataActivity to track data transfer activity, and onDataConnectionStateChanged to request notifications for data connection state changes. Listing 12-12 shows both handlers overridden, with switch statements demonstrating each of the...
Creating a New Visual Interface
The base View class presents a distinctly empty 100-pixel-by-100-pixel square. To change the size of the control and display a more compelling visual interface, you need to override the onMeasure and onDraw methods. Within onMeasure the new View will calculate the height and width it will occupy given a set of boundary conditions. The onDraw method is where you draw on the Canvas. Listing 4-10 shows the skeleton code for a new View class, which will be examined and developed further in the...
Using Context Menus
Context Menus are contextualized by the currently focused View and are triggered by the user's pressing the trackball, middle D-pad button, or a View for around three seconds. You define and populate Context Menus much as you define and populate Activity Menus. There are two options available for creating Context Menus for a particular View. One option is to create a generic ContextMenu object for a View class by overriding a View's onCreateContextMenu handler, as shown here public void...
Where Am I Example
The following example Where Am I features a new Activity that finds the device's current location using the GPS Location Provider. You will expand on this example throughout the chapter as you learn new geographic functionality. This example assumes that you have enabled the gps_provider Location Provider using the techniques shown previously in this chapter, or that you're running it on a device that supports GPS and has that hardware enabled. 1. Create a new Where Am I project with a WhereAmi...
Forward Geocoding
Forward geocoding or just geocoding determines map coordinates for a given location. What constitutes a valid location varies depending on the locale geographic area within which you're searching. Generally, it will include regular street addresses of varying granularity from country to street name and number , postcodes, train stations, landmarks, and hospitals. As a general guide, valid search terms will be similar to the addresses and locations you can enter into the Google Maps search bar....
Reading Data Connection and Transfer State
Using the getDataState and getDataActivity methods you can find the current data connection state and transfer activity respectively as shown in Listing 12-4. Generally it will be more useful to detect changes in the data connection or transfer status. You'll learn how to monitor both later in this chapter. LISTING 12-4 Reading phone data connection and transfer state int dataActivity telephonyManager.getDataActivity int dataState telephonyManager.getDataState case...
Using Intent Filters for PlugIns and Extensibility
You've now learned how to create implicit Intents to launch Activities, but that's only half the story. Android also lets future packages provide new functionality for existing applications, using Intent Filters to populate menus dynamically at run time. This provides a plug-in model for your Activities that lets them take advantage of future functionality, provided through application components you haven't yet conceived of, without your having to modify or recompile your projects. The...
Using Custom Controls
Having created your own custom Views, you can use them within code and layouts as you would any other View. Listing 4-15 shows you how to override the onCreate method in order to add the CompassView, created in the preceding example, to an Activity. public void onCreate Bundle savedInstanceState super.onCreate savedInstanceState CompassView cv new CompassView this setContentView cv To use the same control within a layout resource, specify the fully qualified class name when you create a new...
Extracting Results from a Cursor
To extract values from a result Cursor, first use the moveTo lt location gt methods described earlier to position the cursor at the correct row of the result Cursor. Then use the type safe get lt type gt methods passing in a column index to return the value stored at the current row for the specified column, as shown in the following snippet. String columnValue myResult.getString columnIndex Database implementations should publish static constants that provide the column names and or indexes...
Using Intents to Import System Preference Screens
As well as your own Preference Screens, preference hierarchies can include Preference Screens from other applications including system Preference Screens. You can invoke any Activity within your Preference Screen using an Intent. If you add an Intent node within any Preference Screen element, the system will interpret this as a request to call startActivity using the specified action. This is particularly useful for including links to relevant system Preference Screens within your own...
Fundamental Android Ui Design
User interface UI design, user experience UX , human computer interaction HCI , and usability are huge topics that aren't covered in great depth in this book. Nonetheless, it's important that you get them right when creating your user interfaces. Android introduces some new terminology for familiar programming metaphors that will be explored in detail in the following sections gt Views Views are the base class for all visual interface elements commonly known as controls or widgets . All UI...
Creating a Wallpaper Service Engine
The WallpaperService.Engine class is where you create the Live Wallpaper itself. The Wallpaper Service Engine encapsulates a Surface which is used to display the wallpaper and handle touch events. A Surface is a specialized drawing canvas that supports updates from background threads, making it ideal for creating smooth, dynamic, and interactive graphics. Both the Surface View, and handling touch events, are covered in more detail in Chapter 15. To implement your own Wallpaper Service engine,...
Playing Video Using the Video View
The simplest way to play back video is to use the VideoView control. The Video View includes a Surface on which the video is displayed and encapsulates and manages a Media Player to manage the video playback. The Video View supports the playback of local or streaming video as supported by the Media Player component. Video Views conveniently encapsulate the initialization of the Media Player. To assign a video to play, simply call setVideoPath or setVideoUri to specify the path to a local file,...
Inserting Media into the Media Store
Rather than relying on the Media Scanner you can add new media to the Media Store by creating a new ContentValues object and inserting it into the appropriate Media Store Content Provider yourself. The metadata you specify here can include the title, time stamp, and geocoding information for your new media file, as shown in the code snippet below ContentValues content new ContentValues 3 content.put Audio.AudioColumns.TITLE, TheSoundandtheFury System.currentTimeMillisO 1000 content.put...
Creating Compound Controls
Compound controls are atomic, reusable Views that contain multiple child controls laid out and wired together. When you create a compound control you define the layout, appearance, and interaction of the Views it contains. You create compound controls by extending a ViewGroup usually a layout . To create a new compound control choose the layout class that's most suitable for positioning the child controls, and extend it as shown in Listing 4-6. LISTING 4-6 Creating a compound control...
Using the Simple Cursor Adapter
The SimpleCursorAdapter lets you bind a Cursor to a List View, using a custom layout definition to define the layout of each row item, which is populated by a row's column values. Construct a Simple Cursor Adapter by passing in the current context, a layout resource, a Cursor, and two arrays one that contains the names of the columns to be used, and a second equally-sized array that has resource IDs for the Views to use to display the contents of the corresponding columns. Listing 5-25 shows...
Controlling and Monitoring Camera Settings and Image Options
The camera settings are stored using a Camera.Parameters object, accessible by calling the getParameters method on the Camera object. In order to modify the camera settings, use the set methods on the Parameters object before calling the Camera'setParameters method and passing in the modified Parameters object. LISTING 11-13 Reading and modifying camera settings Available for download on Camera.Parameters parameters camera.getParameters Wrox.com make changes Android 2.0 API level 5 introduced a...
Sending Data Messages
You can send binary data via SMS using the sendDataMessage method on an SMS Manager. The sendDataMessage method works much like sendTextMessage, but includes additional parameters for the destination port and an array of bytes that constitutes the data you want to send. Listing 12-18 shows the basic structure of sending a data message. LISTING 12-18 Sending SMS data messages Available for Intent sentIntent new Intent SENT_SMS_ACTION 'wrox comn PendingIntent sentPI byte data your data...
Transformative Drawables
You can scale and rotate existing Drawable resources using the aptly named ScaleDrawable and RotateDrawable classes. These transformative Drawables are particularly useful for creating progress bars or animating Views. CMlftiiL-.i ne r-d L n y ci u I Re in ui lt i gt gt ScaleDrawable Within the lt scale gt tag, use the scaleHeight and scaleWidth attributes to define the target height and width relative to the bounding box of the original Drawable. Use the scaleGravity attribute to control the...
Sending SMS and MMS from Your Application Using Intents and the Native Client
In many circumstances you may find it easier to pass on the responsibility for sending SMS and MMS messages to another application, rather than implementing a full SMS client within your app. To do so, call startActivity using an Intent with the Intent.ACTION_SENDTO action. Specify a target number using sms schema notation as the Intent data. Include the message you want to send within the Intent payload using an sms_body extra, as shown in Listing 12-13. LISTING 12-13 Sending an SMS message...
Extending and Using the Application Class
Listing 3-7 shows the skeleton code for extending the Application class and implementing it as a singleton. LISTING 3-7 Skeleton application class LISTING 3-7 Skeleton application class Wrax.com import android.content.res.Configuration public class MyApplication extends Application private static MyApplication singleton Returns the application instance public static MyApplication getInstance return singleton public final void onCreate super.onCreate singleton this Once created, you must...
Using Repeating Alarms to Update Earthquakes
In this final modification to the Earthquake example you'll use Alarms to replace the Timer currently used to schedule Earthquake network refreshes. One of the most significant advantages of this approach is that it allows the Service to stop itself when it has completed a refresh, freeing significant system resources. 1. Start by creating a new EarthquakeAlarmReceiver class that extends BroadcastReceiver. package com.paad.earthquake import android.content.BroadcastReceiver import...
Layer Drawable
A LayerDrawable lets you composite several Drawable resources on top of one another. If you define an array of partially transparent Drawables you can stack them on top of one another to create complex combinations of dynamic shapes and transformations. Similarly, you can use Layer Drawables as the source for the transformative Drawable resources described in the preceding section, or the State List and Level List Drawables that follow. Listing 4-21 shows a Layer Drawable. These are defined via...
Replacing the Native Dialer
Replacing the native dialer application involves two steps 1. Intercepting Intents that are currently serviced by the native dialer. 2. Initiating, and optionally managing, outgoing calls. The native dialer application currently responds to Intent actions corresponding to a user's pressing the hardware call button, asking to view data using the tel schema, or making a request to dial a number using the tel schema. To intercept these requests include lt intent-filter gt tags on your new Activity...
Launching the Dialer to Initiate Phone Calls
Best practice is to use Intents to launch a dialer application to initiate new phone calls. Use an Intent action to start a dialer activity you should specify the number to dial using the tel schema as the data component of the Intent. Use the Intent.ACTION_DIAL Activity action to launch a dialer rather than dial the number immediately. This action starts a dialer Activity, passing in the specified number but allowing the dialer application to manage the call initialization the default dialer...
LISTING 921 Creating a custom layout for the Notification status window
lt xml version 1.0 encoding utf-8 gt lt RelativeLayout lt TextView lt RelativeLayout gt lt RelativeLayout gt To assign your custom layout to the Notification, create a new RemoteView object and assign it to the contentView property. You will also need to assign a Pending Intent to the contentlntent property, as shown in Listing 9-22, in which a custom content View is assigned to an ongoing Notification.
Customizing YourToDo List
The to-do list example from Chapter 2 uses TextView controls to represent each row in a List View. You can customize the appearance of the list by extending Text View and overriding the onDraw method. In this example you'll create a new TodoListitemView that will make each item appear as if on a paper pad. When complete, your customized to-do list should look like Figure 4-1. 1. Create a new TodoListItemView class that extends TextView. Include a stub for overriding the onDraw method, and...
Introducing Itemized Overlays and Overlay Items
Overlayitems are used to supply simple maker functionality to your Map Views via the ItemizedOverlay class. itemizedOverlays provide a convenient shortcut for adding markers to a map, letting you assign a marker image and associated text to a particular geographical position. The ItemizedOverlay instance handles the drawing, placement, click handling, focus control, and layout optimization of each Overlayitem marker for you. To add an itemizedOverlay marker layer to your map, start by creating...
Monitoring WiFi Connectivity
The Wi-Fi Manager broadcasts Intents whenever the connectivity status of the Wi-Fi network changes, using an action from one of the following constants defined in the WifiManager class gt wifi_state_changed_action Indicates that the Wi-Fi hardware status has changed, moving between enabling, enabled, disabling, disabled, and unknown. It includes two extra values keyed on extra_wifi_state and extra_previous_state that provide the new and previous Wi-Fi states, respectively. Prepared for ASHLEE...
Creating Resources for Different Languages and Hardware
One of the most compelling reasons to externalize your resources is Android's dynamic resource-selection mechanism. Using the directory structure described below, you can create different resource values for specific languages, locations, and hardware configurations. Android will choose from among these values dynamically at run time. You can specify alternative resource values using a parallel directory structure within the res folder. A hyphen - is used to separate qualifiers that specify the...
Discovering Remote Devices
In this section you'll now learn how to initiate discovery from your local adapter to find discoverable devices nearby. The discovery process can take some time to complete up to 12 seconds . During this time, performance of your Bluetooth Adapter communications will be seriously degraded. Use the techniques in this section to check and monitor the discovery status of the Bluetooth Adapter, and avoid doing high-bandwidth operations including connecting to a new remote Bluetooth Device while...
Emergency Responder SMS Example
In this example, you'll create an SMS application that turns an Android phone into an emergency response beacon. Once finished, the next time you're in unfortunate proximity to an alien invasion or find yourself in a robot-uprising scenario, you can set your phone to automatically respond to your friends' and family members' pleas for a status update with a friendly message or a desperate cry for help . To make things easier for your would-be saviors, you'll use location-based services to tell...
Using Sensors
Listing 14-1 shows the standard pattern for monitoring hardware sensor results. Later sections will take a closer look at orientation and acceleration Sensor implementations in particular. Implement a SensorEventListener. Use the onSensorChanged method to monitor Sensor values and onAccuracyChanged to react to changes in a Sensor's accuracy. LISTING 14-1 Sensor Event Listener skeleton code final SensorEventListener mySensorEventListener new SensorEventListener public void onSensorChanged...
LISTING 1010 Adding a Click Listener to an App Widget Available for
downloadon Intent intent new Wrax.com PendingIntent pendingIntent PendingIntent.getBroadcast this, 0, intent, 0 pendingIntent Using this technique you can add click handlers to one or more of the Views used within your widget, which means you can add support for multiple actions. For example, the standard media player widget assigns different broadcast Intents to several buttons, providing playback control through the play, pause, and next buttons. Changing Image Views Based on Selection Focus...
Bluetooth Data Transfer Example
The following example uses the Android Bluetooth APIs to construct a simple peer-to-peer messaging system that works between two paired Bluetooth devices. Unfortunately the Android emulator can't currently be used to test Bluetooth functionality. In order to test this application you will need to have two physical devices. 1. Start by creating a new BluetoothTexting project featuring a BluetoothTexting Activity. Modify the manifest to include Bluetooth and bluetooth_admin permissions. lt xml...
Getting Started
gt How to install the Android SDK, create a development environment, and debug your projects. gt Understanding mobile design considerations and the importance of optimizing for speed and efficiency and designing for small screens and mobile data connections. gt Using Android Virtual Devices, the emulator, and developer tools. All you need to start writing your own Android applications is a copy of the Android SDK and the Java development kit. Unless you're a masochist, you'll probably want a...







