Whats In This Chapter

> Creating home screen Widgets > Adding search to your applications > Surfacing search results to the Quick Search Box Widgets, Live Folders, Live Wallpaper, and the Quick Search Box let you own a piece of the user's home screen, providing either a window to your application or a stand-alone source of information directly on the home screen. They're an exciting innovation for users and developers, providing the following > Users get instant access to interesting information without...

Monitoring Network Details

The Connectivity Manager provides a high-level view of the available network connections. Using the getActiveNetworkInfo or getNetworkInfo methods, as shown in Listing 13-14, returns NetworkInfo objects that include details on the currently active network or on an inactive network of the type specified. Use the returned NetworkInfo details to find the connection status, network type, and detailed state information of the returned network. STING 13-14 Accessing network information Get the active...

Querying for Content

Content Provider queries take a form very similar to that of database queries. Query results are returned as Cursors over a result set, like databases, in the same way as described previously in this chapter. You can extract values from the result Cursor using the same techniques described within the database section on Extracting Results from a Cursor.'' Using the query method on the ContentResolver object, pass in > The URI of the Content Provider data you want to query. > A projection...

Files Saving State and Preferences

> Persisting simple application data > Saving Activity instance data between sessions > Creating Preference Screens and managing application preferences > Saving and loading files and managing the local file system > Including static files as external resources In this chapter you'll be introduced to two of the simplest but most versatile data persistence techniques in Android Shared Preferences and local files. Saving and loading data are essential for most applications. At a...

Listing 922 Applying a custom layout to the Notification status window

Notification notification new Notification(R.drawable.icon, Custom Content, System.currentTimeMillis()) notification.flags notification.flags Notification.FLAG_ONGOING_EVENT notification.contentView new RemoteViews(this.getPackageName(), R.layout.my_status_window_layout) Intent intent new Intent(this, MyActivity.class) PendingIntent.getActivity(this, 0, intent, 0)) notification.contentlntent pendinglntent Note that when you manually set the contentview property you must also set the...

Types of Android Applications

Most of the applications you create in Android will fall into one of the following categories > Foreground An application that's useful only when it's in the foreground and is effectively suspended when it's not visible. Games and map mashups are common examples. > Background An application with limited interaction that, apart from when being configured, spends most of its lifetime hidden. Examples include call screening applications and SMS auto-responders. > Intermittent Expects some...

Being Fast and Efficient

In a resource-constrained environment, being fast means being efficient. A lot of what you already know about writing efficient code will be just as applicable to Android, but the limitations of embedded systems and the use of the Dalvik VM mean you can't take things for granted. The smart bet for advice is to go to the source. The Android team has published some specific guidance on writing efficient code for Android, so rather than rehash their advice, I suggest you visit and take note of...

Listing 109 Modifying View properties within an App Widget Remote View

Updated Text) Color.BLUE) Update an Image View myBitmap) Update a Progress Bar 100, 50, false) Update a Chronometer SystemClock.elapsedRealtime(), null, true) You can also set the visibility of any View hosted within Remote Views by calling setViewVisibility, as shown here View.VISIBLE) As described in the previous section, once you've made changes to a Remote Views object you must use the App Widget Manager to apply those changes to a particular widget, as shown here views)

Listing 925 Creating an Alarm Available for

Download on int alarmType AlarmManager.ELAPSED_REALTIME_WAKEUP Wrox.com long timeOrLengthofWait 10000 String ALARM_ACTION ALARM_ACTION Intent intentToFire new Intent(ALARM_ACTION) Pendinglntent pendinglntent PendingIntent.getBroadcast(this, 0, intentToFire, 0) alarms.set(alarmType, timeOrLengthofWait, pendingIntent) When the Alarm goes off, the Pending Intent you specified will be broadcast. Setting a second Alarm using the same Pending Intent replaces the preexisting Alarm. To cancel an Alarm,...

Hardware Imposed Design Considerations

Small and portable, mobile devices offer exciting opportunities for software development. Their limited screen size and reduced memory, storage, and processor power are far less exciting, and instead present some unique challenges. Compared to desktop or notebook computers, mobile devices have relatively High costs associated with data transfer Slow data transfer rates with high latency Each new generation of phones improves many of these restrictions. In particular, newer phones have...

Accessing Phone and Network Properties and Status

Access to the telephony APIs is managed by the Telephony Manager, accessible using the getSystemService method as shown in Listing 12-2. LISTING 12-2 Accessing the Telephony Manager Available for String srvcName Context.TELEPHONY_SERVICE Wrox comn TelephonyManager telephonyManager The Telephony Manager provides direct access to many of the phone properties, including device, network, SIM, and data state details.

Using Internet Resources

With Internet connectivity and a WebKit browser, you might well ask if there's any reason to create native Internet-based applications when you could make a web-based version instead. There are a number of benefits to creating thick- and thin-client native applications rather than relying on entirely web-based solutions > Bandwidth Static resources like images, layouts, and sounds can be expensive data consumers on devices with limited and often expensive bandwidth restraints. By creating a...

Adding Notifications and Toasts to the Earthquake Monitor

In the following example, the EarthquakeService is enhanced to trigger a Notification for each new earthquake. As well as displaying a status bar icon, the expanded Notification view will display the magnitude and location of the latest quake, and selecting it will open the Earthquake Activity. 1. Within the EarthquakeService, start by creating a new Notification instance variable to store the Notification object used to control the status bar icon and extended status window item details....

Introducing The Application Manifest

Each Android project includes a manifest file, AndroidManifest.xml, stored in the root of the project hierarchy. The manifest lets you define the structure and metadata of your application, its components, and its requirements. It includes nodes for each of the components (Activities, Services, Content Providers, and Broadcast Receivers) that make up your application and, using Intent Filters and Permissions, determines how they interact with each other and with other applications. The manifest...

Dalvik Debug Monitor Service DDMS

The emulator lets you see how your application will look, behave, and interact, but to really see what's happening under the surface you need the Dalvik Debug Monitoring Service. The DDMS is a powerful debugging tool that lets you interrogate active processes, view the stack and heap, watch and pause active threads, and explore the file system of any connected Android device. The DDMS perspective in Eclipse also provides simplified access to screen captures of the emulator and the logs...

Introducing the Media Player

Multimedia playback in Android is handled by the MediaPlayer class. You can play media stored in application resources, local files, Content Providers, or streamed from a network URL. In each case, the file format and type of multimedia being played is abstracted from you as a developer. The Media Player's management of audio and video files and streams is handled as a state machine. In the most simplistic terms, transitions through the state machine can be described as follows > Initialize...

Accessing the Local Bluetooth Device Adapter

The local Bluetooth device is controlled via the BluetoothAdapter class. To access the default Bluetooth adapter on the host device call getDefaultAdapter, as shown in Listing 13-1. It is possible that some Android devices will feature multiple Bluetooth adapters, though it is currently only possible to access the default device. LISTING 13-1 Accessing the default Bluetooth Adapter Available for downloadon BluetoothAdapter bluetooth BluetoothAdapter.getDefaultAdapter() Wrox.com To read any of...

Finding Location Providers Using Criteria

In most scenarios it's unlikely that you will want to explicitly choose the Location Provider to use. More commonly, you'll specify the requirements thtia provider must meet and let Android determine the best technology to use. Use the Criteria class to dictate the requirements of a provider in terms of accuracy (fine or coarse), power use (low, medium, high), financial cost, and the ability to return values for altitude, speed, and bearing. Listing 8-1 specifies Criteria requiring coarse...

Introducing Dialogs

Dialog boxes are a common UI metaphor in desktop, web, and mobile applications. They're used to help users answer questions, make selections, and confirm actions, and to display warning or error messages. Dialog boxes in Android are partially transparent, floating Activities that partially obscure the Activities that launched them. As in Figure 5-5, they generally obscure the Activities behind them using a blur or dim filter. There are three ways to implement a dialog in Android > Using the...

Using The Manifest Editor

The ADT plug-in includes a visual Manifest Editor so you don't have to manipulate the underlying XML directly. To use the Manifest Editor in Eclipse, right-click the AndroidManifest.xml file in your project folder and select Open With O Android Manifest Editor. This presents the Android Manifest Overview screen, as shown in Figure 3-1. This screen gives you a high-level view of your application structure, enabling you to set your application version information and root level manifest nodes,...

Introducing Layouts

Layout managers (more generally just called layouts) are extensions of the ViewGroup class used to position child controls for your UI. Layouts can be nested, letting you create arbitrarily complex interfaces using a combination of layouts. The Android SDK includes some simple layouts to help you construct your UI. It's up to you to select the right combination of layouts to make your interface easy to understand and use. The following list includes some of the more versatile layout classes...

The Android Debug Bridge ADB

The Android debug bridge (ADB) is a client-service application that lets you connect with an Android Emulator or device. It's made up of three components a daemon running on the emulator, a service that runs on your development hardware, and client applications (like the DDMS) that communicate with the daemon through the service. As a communications conduit between your development hardware and the Android device emulator, the ADB lets you install applications, push and pull files, and run...

Connecting to an Internet Resource

While the details of working with specific web services won't be covered within this book, it's useful to know the general principles of connecting to the Internet, and getting an input stream from a remote data source. Before you can access Internet resources, you need to add an internet uses-permission node to your application manifest, as shown in the following XML snippet < uses-permission Listing 5-26 shows the basic pattern for opening an Internet data stream. String myFeed...

What Makes An Android Application

Android applications consist of loosely coupled components, bound by an application manifest that describes each component and how they all interact, as well as the application metadata including its hardware and platform requirements. The following six components provide the building blocks for your applications > Activities Your application's presentation layer. Every screen in your application will be an extension of the Activity class. Activities use Views to form graphical user...

Creating Applications and Activities

> An introduction to the Android application components and the different types of Android applications you can build with them > The Android application life cycle > How to create and annotate the application manifest > How to use external resources to provide dynamic support for locations, languages, and hardware configurations > How to implement and use your own Application class > How to create new Activities > Understanding an Activity's state transitions and life cycle...

Native Preference Controls

Android includes several preference controls to build your Preference Screens > CheckBoxPreference A standard preference checkbox control. Used to set preferences to true or false. > EditTextPreference Allows users to enter a string value as a preference. Selecting the preference text will display a text entry dialog. > ListPreference The preference equivalent of a spinner. Selecting this preference will display a dialog box containing a list of values from which to select. You can...

Creating an Earthquake Live Folder

In the following example you'll extend the Earthquake application again, this time to include a Live Folder that displays the magnitude and location of each quake. 1. Start by modifying the EarthquakeProvider class. Create a new static URI definition that will be used to return the Live Folder items. public static final Uri LIVE_FOLDER_URI 2. Modify the uriMatcher object and getType method to check for this new URI request. private static final int LIVE_FOLDER 3 uriMatcher new...

Geocoding Where Am I

Using the Geocoder you can determine the street address at your current location. In this example you'll further extend the Where Am I project to include and update the current street address whenever the device moves. Start by modifying the manifest to include the Internet uses-permission < uses-permission Then open the WhereAmI Activity. Modify the updateWithNewLocation method to instantiate a new Geocoder object, and call the getFromLocation method, passing in the newly received location...

Finding and Using the Launch Intent Within an Activity

When an application component is started through an implicit Intent, it needs to find the action it's to perform and the data to perform it on. Call the getIntent method usually from within the onCreate method to extract the Intent used to start a component, as in Listing 5-8. STING 5-8 Finding the launch Intent in a sub-Activity public void onCreate(Bundle icicle) super.onCreate(icicle) setContentView(R.layout.main) Use the getData and getAction methods to find the data and action associated...

Using Intent Filters to Service Implicit Intents

If an Intent is a request for an action to be performed on a set of data, how does Android know which application (and component) to use to service the request Intent Filters are used to register Activities, Services, and Broadcast Receivers as being capable of performing an action on a particular kind of data. Intent Filters are also used to register Broadcast Receivers as being interested in Intents broadcasting a given action or event. Using Intent Filters, application components announce...

Summary

This chapter showed you how to download and install the Android SDK, create a development environment using Eclipse on Windows, Mac OS, or Linux platforms, and create run and debug configurations for your projects. You learned how to install and use the ADT plug-in to simplify the creation of new projects and streamline your development cycle. You were introduced to some of the design considerations involved in developing mobile applications, particularly the importance of optimizing for speed...

Telephony and SMS

> Reading the phone, network, data connectivity, and SIM states > Monitoring changes to the phone, network, data connectivity, and SIM states > Using Intents to send SMS and MMS messages > Using the SMS Manager to send SMS Messages > Handling incoming SMS messages In this chapter, you'll learn to use Android's telephony APIs to monitor mobile voice and data connections as well as incoming and outgoing calls, and to send and receive SMS (short messaging service) messages. You'll take a...

Bluetooth Networks and WiFi

> Managing Bluetooth devices > Discovering remote Bluetooth devices > Communicating over Bluetooth > Monitoring Internet connectivity > Obeying user preferences for background data transfer > Monitoring Wi-Fi and network details > Configuring networks and Wi-Fi configurations > Scanning for Wi-Fi access points In this chapter you'll continue to explore Android's low-level communications APIs by examining the Bluetooth, network, and Wi-Fi packages. Android offers APIs to manage...

Get more out of wroxcom

Take an active role online by participating in our P2P forums p2p.wrox.com Hundreds of our books are available online through Books24x7.com Download short informational pieces and code to keep you up to date and out of trouble Sign up for our free monthly newsletter at newsletter.wrox.com Ready for more Wrox We have books and e-books available on .NET, SQL Server, Java, XML, Visual Basic, C C++, and much more We always like to get feedback from our readers. Have a book idea ANDROID 2...

Sensors

> The available sensor-types > Monitoring sensors and interpreting sensor values > Using the compass, accelerometer, and orientation sensors > Remapping your orientation reference frame > Controlling device vibration Modern mobile phones are much more than simple communications devices with a connection to the Internet. With microphones, cameras, accelerometers, compasses, temperature gauges, and brightness detectors, smartphones have become extra-sensory devices, able to augment your...

Android Development Tools

The Android SDK includes several tools and utilities to help you create, test, and debug your projects. A detailed examination of each developer tool is outside the scope of this book, but it's worth briefly reviewing what's available. For more detail than is included here, check out the Android documentation at As mentioned earlier, the ADT plug-in conveniently incorporates most of these tools into the Eclipse IDE, where you can access them from the DDMS perspective, including > The Android...

Native Android Actions

Native Android applications also use Intents to launch Activities and sub-Activities. The following non-comprehensive list shows some of the native actions available as static string constants in the Intent class. When creating implicit Intents you can use these actions, called Activity Intents, to start Activities and sub-Activities within your own applications. Later you will be introduced to Intent Filters and you'll learn how to register your own Activities as handlers for these actions....

The Android Application Life Cycle

Unlike most traditional environments, Android applications have limited control over their own life cycles. Instead, application components must listen for changes in the application state and react accordingly, taking particular care to be prepared for untimely termination. By default, each Android application runs in its own process, each of which is running a separate instance of Dalvik. Memory and process management is handled exclusively by the run time. While it's uncommon, it's possible...

Hello Android

> A background to mobile application development > What Android is (and what it isn't) > An introduction to the Android SDK features > What devices Android runs on > Why develop for mobile and Android > An introduction to the SDK and the Android development framework Whether you're an experienced mobile engineer, a desktop or web developer, or a complete programming novice, Android represents an exciting new opportunity to write innovative applications for mobile devices. Despite...

Using the Provider

You can now update the Earthquake Activity to use the Earthquake Provider to store quakes and use them to populate the List View. 1. Within the Earthquake Activity, update the addNewQuake method. It should use the application's Content Resolver to insert each new Earthquake into the provider. Move the existing array control logic into a separate addQuakeToArray method. private void addNewQuake Quake _quake ContentResolver cr getContentResolver Construct a where clause to make sure we don't...

Menu Item Options

Android supports most of the traditional Menu Item options you're probably familiar with, including icons, shortcuts, checkboxes, and radio buttons, as listed here gt Checkboxes and radio buttons Checkboxes and radio buttons on Menu Items are visible in expanded menus and submenus, as shown in Figure 4-9. To set a Menu Item as a checkbox, use the setCheckable method. The state of that checkbox is controlled via setChecked. A radio button group is a group of items displaying circular buttons, in...

Working With Sqlite Databases

It's good practice to create a helper class to simplify your database interactions. The following section shows you how to create a database adapter class for your database. This abstraction layer encapsulates your database interactions. It will provide intuitive, strongly typed methods for adding, removing, and updating items. A database adapter should also handle queries and expose methods for creating, opening, and closing the database. Prepared for ASHLEE KABAT, email akabat spam.la Order...

Automating the Emergency Responder

In the following example, you'll fill in the code behind the Setup Auto Responder button added in the previous example, to let the Emergency Responder automatically respond to status update requests. 1. Start by creating a new autoresponder.xml layout resource that will be used to lay out the automatic response configuration window. Include an EditText for entering a status message to send, a Spinner for choosing the auto-response expiry time, and a checkBox to let users decide whether they...

Creating a Compass View Example

Android Drawcircle Drawline Example

In the following example you'll create a new Compass View by extending the View class. This View will display a traditional compass rose to indicate a heading orientation. When complete, it should appear as in Figure 4-2. A compass is an example of a UI control that requires a radically different visual display from the Text Views and Buttons available in the SDK toolbox, making it an excellent candidate for building from scratch. In Chapter 14 you'll use this Compass View and the device's...

Creating the Content Provider

First open the Earthquake project and create a new EarthquakeProvider class that extends ContentProvider. Include stubs to override the onCreate, getType, query, insert, delete, and update methods. import android.database.SQLException import import import public class EarthquakeProvider extends ContentProvider Override public Cursor query Uri url, String projection, String selection, String selectionArgs, String sort public Uri insert Uri _url, ContentValues _initialValues public int delete...

Audio Video and Using the Camera

gt Playing audio and video with the Media Player gt Packaging audio as an application resource gt Using the Video View for video playback gt Recording audio and video with the Media Recorder gt Recording video and taking pictures using Intents gt Previewing recorded video and displaying live camera streams gt Taking pictures and controlling the camera gt Reading and modifying image EXIF data gt Adding media to the Media Store The only modern technology that can compete with mobile phones for...

Using Intents to Take Pictures

The easiest way to take a picture using the device camera is using the action_image_capture Media Store static constant in an Intent passed to startActivityForResult. startActivityForResult new This will launch the camera Activity, allowing users to modify the image settings manually, and preventing you from having to rewrite the entire camera application. The image capture action supports two modes, thumbnail and full image. gt Thumbnail By default, the picture taken by the image capture...

Creating a Map Based Activity

To use maps in your applications you need to extend MapActivity. The layout for the new class must then include a MapView to display a Google Maps interface element. The Android maps library is not a standard Android package as an optional API, it must be explicitly included in the application manifest before it can be used. Add the library to your manifest using a uses-library tag within the application node, as shown in the following XML snippet lt uses-library The maps package as described...

Saving and Restoring Instance State

To save Activity instance variables, Android offers a specialized variation of Shared Preferences. By overriding an Activity's onSaveInstanceState event handler, you can use its Bundle parameter to save UI instance values. Store values using the same get and put methods as shown for Shared Preferences, before passing the modified Bundle into the superclass's handler, as shown in Listing 6-6. LISTING 6-6 Saving Activity instance state download on private static final String TEXTVIEW_STATE_KEY...

Specifying Supported Screen Sizes

For some applications it may not be possible to optimize your UI to support all possible screen sizes. You can use the lt supports-screens gt manifest element to specify which screens your application can be run on, as shown in Listing 4-25. LISTING 4-25 Manifest element supporting normal and large screen sizes Available for download on lt supports-screens android largeScreens true android anyDensity true In this context a small screen is any display with resolution smaller than HVGA. A large...

Using System Resources

The native Android applications externalize many of their resources, providing you with various strings, images, animations, styles, and layouts to use in your applications. Accessing the system resources in code is similar to using your own resources. The difference is that you use the native Android resource classes available from android.R, rather than the application-specific R class. The following code snippet uses the getString method available in the application context to retrieve an...

Vibrating the Phone

You can use the phone's vibration function to execute a vibration pattern specific to your Notification. Android lets you control the pattern of a vibration you can use vibration to convey information as well To set a vibration pattern, assign an array of longs to the Notification'vibrate property. Construct the array so that values representing the length of time in milliseconds to vibrate alternate with values representing the length of time to pause. Before you can use vibration in your...

Updating Your Location in Where Am I

In the following example, the Where Am I project is enhanced to track your current location by listening for location changes. Updates are restricted to one every two seconds, and only when movement of more than 10 meters has been detected. Rather than explicitly selecting the GPS provider, in this example you'll create a set of Criteria and let Android choose the best provider available. 1. Start by opening the WhereAmI Activity in the Where Am I project. Update the onCreate method to find the...

Using the Media Store Provider

The Android Media Store is a managed repository of audio, video, and image files. Whenever you add a new multimedia file to the file system, it should also be added to the Media Store. This will expose it to other applications, including the default media player. Chapter 11 shows you how to use the Content Scanner to add new media to the Media Store. To access media from the Media Store, query the image, video, or audio Content Providers using the techniques described earlier within this...

Using Scalable Graphics Assets

Earlier in this chapter you were introduced to a number of Drawable resources, most of which can be defined in XML and all of which can be scaled smoothly by the run time, regardless of the screen size or pixel density. Where possible, use the following Drawable resources rather than fixed bitmap assets V Composite and transformative Drawables such as Remember when defining these assets to use density-independent pixels dp . Using scalable assets has the advantage of generic support for...

Managing Device Discoverability

In order for remote Android Devices to find your local Bluetooth Adapter during a discovery scan, you need to ensure that it is discoverable. The Bluetooth Adapter's discoverability is indicated by its scan mode. You can find the adapter's scan mode by calling getScanMode on the BluetoothAdapter object. It will return one of the following BluetoothAdapter constants Inquiry scan and page scan are both enabled, meaning that the device is discoverable from any Bluetooth device performing a...

Listing 927 Setting repeating alarms

Fire an intent exactly every hour if already awake. 60 60 1000, 60 60 1000, elapsedIntent Wakeup and fire an alarm about every hour 60 60 1000, AlarmManager.INTERVAL_DAY, elapsedIntent The battery impact of setting regularly repeating alarms can be significant. It is good practice to limit your alarm frequency to the sloivest acceptable rate, wake the device only if necessary, and use the inexact repeating alarm whenever possible.

Supported Android Sensors

The following is a list of the sensor-types currently available note that the hardware on the host device determines which of these sensors are actually available to your application. gt Sensor.TYPE_ACCELEROMETER A three-axis accelerometer sensor that returns the current acceleration along three axes in m s2. The accelerometer is explored in greater detail later in this chapter. gt Sensor.TYPE_GYROSCOPE A gyroscopic sensor that returns the current device orientation on three axes in degrees. gt...

Referring to Styles in the Current Theme

Using themes is an excellent way to ensure consistency for your application's UI. Rather than fully define each style, Android provides a shortcut to let you use styles from the currently applied theme. To do this you use android rather than as a prefix to the resource you want to use. The following example shows a snippet of the preceding code but uses the current theme's text color rather than an external resource. This technique lets you create styles that will change if the current theme...

Saving the ToDo List Activity State

Currently, each time the To-Do List example application is restarted, all the to-do items are lost and any text entered into the text entry box is cleared. In this example you'll start to save the application state of the To-Do List application across sessions. The instance state in the ToDoList Activity consists of three variables gt Is a new item being added gt What text exists in the new item entry textbox gt What is the currently selected item Using the Activity's default Shared Preference...

Listing 815 Pinning a View to a geographical location

Double lat 37.422134 1E6 Double lng -122.084069 1E6 GeoPoint geoPoint new GeoPoint lat.intValue , lng.intValue geoLP new MapView.LayoutParams.WRAP_CONTENT, geoPoint, EditText editText2 new EditText getApplicationContext editText2.setText Location Pinned Panning the map will leave the first Textview stationary in the upper left corner, while the second Textview will move to remain pinned to a particular position on the map. To remove a View from a Map View, call removeView, passing in the View...

Mapping Where Am I

In the following code example the Where Am I project is extended again. This time you'll add mapping functionality by transforming it into a Map Activity. As the device location changes, the map will automatically re-center on the new position. 1. Start by adding the lt uses-permission gt tag for Internet access to the application manifest. Also import the Android maps library within the application tag. lt xml version 1.0 encoding utf-8 gt lt uses-library lt action gt lt category gt lt...

Runtime Configuration Changes

Android handles runtime changes to the language, location, and hardware by terminating and restarting each application and reloading the resource values. This default behavior isn't always convenient or desirable, particularly as some configuration changes like those to screen orientation and keyboard availability can occur as easily as a user can rotate the device or slide out the keyboard. You can customize your application's response to such changes by detecting and reacting to them...

Introducing the SQLite OpenHelper

SQLiteOpenHelper is an abstract class used to implement the best practice pattern for creating, opening, and upgrading databases. By implementing an SQLite Open Helper you hide the logic used to decide if a database needs to be created or upgraded before it's opened. Listing 7-1 showed how to extend the SQLiteOpenHelper class by overriding the constructor, onCreate, and onUpgrade methods to handle the creation of a new database and upgrading to a new version, respectively. In the previous...

Creating and Using a Widget Configuration Activity

Android Appwidgetmanager

In some cases an App Widget will be significantly more useful if the user is given the opportunity to customize the data it displays and how the data is displayed. This is particularly important given that multiple instances of the same widget can be added to the home screen. An App Widget configuration Activity is an Activity that is launched immediately when a widget is added to the home screen. It can be any Activity within your application, provided it has an Intent Filter for the...

Flashing the Lights

Notifications also include properties to configure the color and flash frequency of the device's LED. Each device may have different limitations with regard to control over the LED. Where the color you specify is not available, as close an approximation as possible will be used. When using LEDs to convey information to the user keep this limitation in mind and avoid making it the only way such information is made available. The ledARGB property can be used to set the LED's color, while...

An Earthquake Monitoring Service Example

In this chapter you'll modify the Earthquake example you started in Chapter 5 and continued to enhance in Chapters 6, 7, and 8 . In this example you'll move the earthquake updating and processing functionality into a separate Service component. Prepared for ASHLEE KABAT, email akabat spam.la Order number 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this...

Saving Simple Application Data

The data-persistence techniques in Android provide options for balancing speed, efficiency, and robustness. gt Shared Preferences When storing UI state, user preferences, or application settings, you want a lightweight mechanism to store a known set of values. Shared Preferences let you save groups of key value pairs of primitive data as named preferences. gt Saved Application State Activities include specialized event handlers to record the current UI state when your application is moved to...

Creating Your Widget Intent Receiver and Adding It to the Application Manifest

Widgets are implemented as Intent Receivers with Intent Filters that catch broadcast Intents, which request widget updates using the AppWidget.ACTION_APPWIDGET_UPDATE, deleted, enabled, and DiSABLED actions. You can create your widget by extending the intentReceiver class directly and interpreting those broadcast Intents by overriding the onReceive method. The AppWidgetProvider class provides a simplified alternative by encapsulating the Intent processing and presenting you with event handlers...

Recording Sound with Audio Record

Use the AudioRecord class to record audio directly from the hardware buffers. Create a new Audio Record object, specifying the source, frequency, channel configuration, audio encoding, and buffer size. int bufferSize channelConfiguration, audioEncoding AudioRecord audioRecord new frequency, channelConfiguration, audioEncoding, bufferSize For privacy reasons, Android requires that the record_audio manifest permission be included in your manifest. lt uses-permission The frequency, audio encoding,...

Introducing SQLite Databases

Using SQLite you can create independent relational databases for your applications. Use them to store and manage complex, structured application data. Android databases are stored in the folder on your device or emulator . By default all databases are private, accessible only by the application that created them. Database design is a big topic that deserves more thorough coverage than is possible within this book. It is worth highlighting that standard database best practices still apply in...

Introducing the Connectivity Manager

The ConnectivityManager represents the Network Connectivity Service. It's used to monitor the state of network connections, configure failover settings, and control the network radios. To access the Connectivity Manager, use getSystemService, passing in Context.CONNECTIVITY_ service as the service name, as shown in Listing 13-12. LISTING 13-12 Accessing the Connectivity Manager Prepared for ASHLEE KABAT, email akabat spam.la Order number 56760408 This PDF is for the purchaser's personal use in...

Creating A Settings Activity For The Earthquake Viewer

In Chapter 5 you created an earthquake monitor that showed a list of recent earthquakes based on an RSS feed. In the following example you'll build an Activity to set application preferences for this earthquake viewer. It will let users configure settings for a more personalized experience. You'll provide the option to toggle automatic updates, control the frequency of updates, and filter the minimum earthquake magnitude displayed. Later in this chapter you'll replace this Activity with a...

Using Intents to Record Video

The easiest way to initiate video recording is using the ACTION_VIDEO_CAPTURE Media Store static constant in an Intent passed to startActivityForResult. startActivityForResult new This will launch the native video camera Activity, allowing users to start, stop, review, and retake their video, and preventing you from having to rewrite the entire video camera application. The video capture action supports two optional extras, available as static constants from the MediaStore class gt extra_output...

Customizing theToDo List Array Adapter

This example extends the To-Do List project, storing each item as a ToDoitem object that includes the date each item was created. You will extend ArrayAdapter to bind a collection of ToDoItem objects to the ListView and customize the layout used to display each List View item. 1. Return to the To-Do List project. Create a new ToDoItem class that stores the task and its creation date. Override the toString method to return a summary of the item data. import java.text.SimpleDateFormat import...

Reading and Writing Jpeg Exif Image Details

The ExifInterface class provides mechanisms for you to read and modify the EXIF Exchangeable Image File Format data stored within a JPEG file. Create a new ExifInterface instance by passing the full filename in to the constructor. ExifInterface exif new ExifInterface filename EXIF data is used to store a wide range of metadata on photographs, including date and time, camera settings such as make and model , and image settings such as aperture and shutter speed , as well as image descriptions...

Using the Media Recorder

Multimedia recording is handled by the aptly named MediaRecorder class. You can use it to record audio and or video files that can be used in your own applications, or added to the Media Store. To record audio or video, create a new Media Recorder object. MediaRecorder mediaRecorder new MediaRecorder Before you can record any media in Android, your application needs the record_audio and or record_video permissions. Add uses-permission tags for each of them, as required, in your application...

Opening a Bluetooth Server Socket Listener

A Bluetooth Server Socket is used to listen for incoming Bluetooth Socket connection requests from remote Bluetooth Devices. In order for two Bluetooth devices to be connected, one must act as a server listening for and accepting incoming requests and the other as a client initiating the request to connect to the server . Once the two are connected, the communications between the server and host device are handled through a Bluetooth Socket at both ends. To listen for incoming connection...

Creating and Using Overlays

Overlays enable you to add annotations and click handling to MapViews. Each Overlay lets you draw 2D primitives, including text, lines, images, and shapes, directly onto a canvas, which is then overlaid onto a Map View. You can add several Overlays onto a single map. All the Overlays assigned to a Map View are added as layers, with newer layers potentially obscuring older ones. User clicks are passed through the stack until they are either handled by an Overlay or registered as clicks on the...

Autosync

Applications sync data aulnmalically Manaje accounts This value is enforced at the application level, meaning that you are responsible for reading the value and adhering to the user's preference for allowing background data transfers. To obtain the background data setting, call the getBackgroundDataSetting method on the Connectivity Manager object boolean backgroundEnabled If the background data setting is disabled, your application should transfer data only when it is active and in the...

Sending SMS Messages Manually

SMS messaging in Android is handled by the SmsManager. You can get a reference to the SMS Manager using the static method SmsManager.getDefault, as shown in the following snippet. SmsManager smsManager SmsManager.getDefault Prior to Android 1.6 SDK level 4 the SmsManager and SmsMessage classes were provided by the android.telephony.gsm package. These have now been deprecated and the SMS classes moved to android.telephony to ensure generic support for GSM and CDMA devices. To send SMS messages,...

Including Static Files As Resources

If your application requires external file resources, you can include them in your distribution package by placing them in the res raw folder of your project hierarchy. To access these read-only file resources, call the openRawResource method from your application's Resource object to receive an InputStream based on the specified file. Pass in the file name without extension as the variable name from the R.raw class, as shown in the following skeleton code Resources myResources getResources...

Externalizing Resources

No matter what your development environment, it's always good practice to keep non-code resources like images and string constants external to your code. Android supports the externalization of resources ranging from simple values such as strings and colors to more complex resources like images Drawables , animations, and themes. Perhaps the most powerful externalizable resources are layouts. Prepared for ASHLEE KABAT, email akabat spam.la Order number 56760408 This PDF is for the purchaser's...

Implicit Intents and Late Runtime Binding

An implicit Intent is a mechanism that lets anonymous application components service action requests. That means you can ask the system to launch an Activity that can perform a given action without knowing which application, or Activity, will do so. When constructing a new implicit Intent to use with startActivity, you nominate an action to perform and, optionally, supply the URI of the data to perform that action on. You can also send additional data to the target Activity by adding extras to...

Listening for Broadcasts with Broadcast Receivers

Broadcast Receivers are used to listen for broadcast Intents. For a Broadcast Receiver to be needs to be registered, either in code or within the application manifest. When registering a Receiver you must use an Intent Filter to specify which Intents it is listening for. To create a new Broadcast Receiver, extend the BroadcastReceiver class and override the onReceive event handler as shown in Listing 5-18. LISTING 5-18 Broadcast Receiver skeleton implementation import...

Creating An Earthquake Viewer

In the following example you'll create a tool that uses a USGS earthquake feed to display a list of recent earthquakes. You will return to this earthquake application several times, first in Chapters 6 and 7 to save preferences and share the earthquake data with a Content Provider, and again in Chapters 8 and 9 to add mapping support and to move the earthquake updates into a Service. In this example you'll create a list-based Activitythat connects to an earthquake feed and displays the...

Introducing Accelerometers

Onsensorchanged Pitch Roll

Accelerometers, as their name suggests, are used to measure acceleration. They are also sometimes referred to as gravity sensors. Accelerometers are also known as gravity sensors because of their inability to differentiate betiveen acceleration caused by movement and gravity. As a result, an accelerometer detecting acceleration on the z-axis up down will read -9.8m s1 when it's at rest this value is available as the SensorManager.STANDARD_GRAVITY constant . Acceleration is defined as the rate...

Monitoring Network Connectivity

One of the most useful functions of the Connectivity Manager is to notify applications of changes in network connectivity. To monitor network connectivity create your own Broadcast Receiver implementation that listens for ConnectivityManager.CONNECTIVITY_ACTION broadcast Intents. Such Intents include several extras that provide additional details on the change to the connectivity state. You can access each extra using one of the static constants available from the ConnectivityManager class gt...

Creating Custom Link Strings

To define your own linkify strings you create a new RegEx pattern to match the text you want to display as hyperlinks. As with the native types, you linkify the target View by calling Linkify.addLinks, but this time pass in the new RegEx pattern. You can also pass in a prefix that will be prepended to the target URI when a link is clicked. Listing 5-14 shows a View being linkified to support earthquake data provided by an Android Content Provider that you will create in Chapter 7 . Rather than...

Creating A Standard Preference Activity For The Earthquake Viewer

Previously in this chapter you created a custom Activity to let users modify the application settings for the earthquake viewer. In this example you'll replace this custom Activity with the standard application settings framework described in the previous section. 1. Start by creating a new XML resource folder at res xml. Within it create a new userprefer-ences.xml file. This file will define the settings UI for your earthquake application settings. Use the same controls and data sources as in...

Understanding Application Priority And Process States

The order in which processes are killed to reclaim resources is determined by the priority of the hosted applications. An application's priority is equal to its highest-priority component. If two applications have the same priority, the process that has been at a lower priority longest will be killed first. Process priority is also affected by interprocess dependencies if an application has a dependency on a Service or Content Provider supplied by a second application, the secondary application...

Gradient Drawable

A GradientDrawable lets you design complex gradient fills. Each gradient defines a smooth transition between two or three colors in a linear, radial, or sweep pattern. Gradient Drawables are defined using the lt gradient gt tag as a subnode within a Shape Drawable definition such as those defined above . Each Gradient Drawable requires at least a startColor and endColor attribute and supports on optional middleColor. Using the type attribute you can define your gradient as one of the following...

Widget Design Guidelines

Widgets are often displayed alongside both native and third-party widgets, so it's important that yours conform to design standards. This is particularly important because widgets are most often used on the home screen. There are widget UI design guidelines for controlling both layout size and visual styling. The former is rigidly enforced while the latter is a guide only both are summarized in the following sections. Additional detail can also be found on the Android Developers Widget Design...

Moving the Earthquake Service to a Background Thread Using Async Task

The following example shows how to move the network lookup and XML processing done in the EarthquakeService onto a background thread using an AsyncTask. 1. Create a new AsyncTask implementation, EarthquakeLookupTask, specifying Void for the input parameters and result variable types, and Quake for the progress reporting. Include stubs that override dolnBackground, onProgressUpdate, and onPostExecute. private class EarthquakeLookupTask extends AsyncTask lt Void, Quake, Void gt Override protected...

State List Drawables

A State List Drawable is a composite resource that enables you to specify a different Drawable to display based on the state of the View to which it has been assigned. Most native Android Views use State List Drawables, including the image used on Buttons and the background used for standard List View items. To define a State List Drawable, create an XML file that specifies an alternative Drawable resource for each selection state required, as shown in Listing 4-22. download on lt selector com...

Level List Drawables

Using a Level List Drawable you can effectively overlay several Drawable resources, specifying an integer index value for each layer, as shown in Listing 4-23. LISTING 4-23 Level List Drawable resource LISTING 4-23 Level List Drawable resource lt level-list xmlns android lt item android maxLevel lt item android maxLevel lt item android maxLevel lt item android maxLevel lt item android maxLevel lt item android maxLevel lt item android maxLevel lt level-list gt To select which image to display in...

Live Folder Activity

The Live Folder itself is created with an Intent returned as a result from an Activity. The Intent's data property indicates the URI of the Content Provider supplying the data with the appropriate projection applied , while a series of extras are used to configure settings such as the display mode, icon, and folder name. Listing 10-16 shows the overridden onCreate method of an Activity used to create a Live Folder. The Live Folder definition Intent is constructed and set as the Activity result,...

The Native Linkify Link Types

The static Linkify.addLinks method accepts the View to linkify, and a bitmask of one or more of the default content types supported and supplied by the Linkify class web_urls, email_addresses, Listing 5-12 shows how to linkify a Text View to display web and e-mail addresses as hyperlinks. When clicked, they will open the browser and an e-mail application respectively. LISTING 5-12 Using Linkify in code Available for downloadon TextView textView Wrox.com Linkify.addLinks textView, Most Android...

How Android Resolves Intent Filters

When you use startActivity, the implicit Intent passed in usually resolves to a single Activity. If there are multiple Activities capable of performing the given action on the specified data, the user will be presented with a list of alternatives. The process of deciding which Activity to start is called Intent resolution. The aim of Intent resolution is to find the best Intent Filter match possible by means of the following process 1. Android puts together a list of all the Intent Filters...

Playing Sound with Audio Track

Use the AudioTrack class to play raw audio directly into the hardware buffers. Create a new Audio Track object, specifying the streaming mode, frequency, channel configuration, and the audio encoding type and length of the audio to play back. AudioTrack audioTrack new Because this is raw audio, there is no meta-data associated with the recorded files, so it's important to correctly set the audio data properties to the same values as those used when recording the file. When your Audio Track is...