Listing 116 srccomcookbookadvancendkndkjava

Import android.app.Activity import android.widget.TextView import android.os.Bundle public class ndk extends Activity Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState) TextView tv new TextView(this) tv.setText( native calculation on factorial +factorial(30)) setContentView(tv) public static native int factorial(int n) static native calculation on factorial 1409286144 Figure 11.2 Output of the NDK application.

Android Custom View

As discussed in Chapter 4,User Interface Layout,Android has two types of views View objects and ViewGroup objects.A custom view can be created by either starting from scratch or inheriting an existing view structure. Some standard widgets are defined by the Android Framework under the View and ViewGroup class, and if possible, the customization should start with one of these Views Button, EditText, TextView, ImageView, and so on ViewGroups LinearLayout, ListView, RelativeLayout, RadioGroup, and...

The Android Developers Cookbook

Building Applications with the Android SDK Upper Saddle River, NJ Boston Indianapolis San Francisco New York Toronto Montreal London Munich Paris Madrid Cape Town Sydney Tokyo Singapore Mexico City Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. Ihe...

Recipe Setting Relative Layout and Layout ID

Sometimes it is more convenient to set the layout relative to a starting object or parent object rather than absolute rules. Also, if the UI starts nesting LinearLayouts, it might be simpler to use relative layouts.This can be done using a RelativeLayout view, as shown in Listing 4.3.The layout is shown in Figure 4.7. Figure 4.7 Four text views from the RelativeLayout example. < xml version 1.0 encoding utf-8 > < RelativeLayout < TextView android id +id mid android text middle <...

Content Provider

Every application has its own sandbox and cannot access data from other applications. If access to functions not provided by its own sandbox is required, the application must explicitly declare permission upfront before installation. Android provides an interface called ContentProvider to act as a bridge between applications, enabling them to share and change each other's data.A content provider allows a clean separation between the application layer and data layer. It requires a permission...

Recipe Launching Another Activity from an Event

In this recipe, MenuScreen is the main activity as shown in Listing 2.8. It launches the PlayGame activity. Here the trigger event is implemented as a button click using the Button widget. When a user clicks the button, the startGame() function runs it launches the PlayGame activity. When a user clicks the button in the PlayGame activity, it calls finish() to return control to the calling activity. The steps for launching an activity are 1. Declare an Intent that points to the activity to be...

Recipe Specifying a Run Configuration

The run configuration is a separate profile for each application. It tells Eclipse how to run the project, start the Activity, and whether to install the application on the emulator or a connected device. The ADT automatically creates a run configuration for each application when it is first created, but it can be customized as described here. To create a new run configuration or edit an existing one, select Run Run Configurations (or Debug Configurations ) in Eclipse to launch the Run...

Recipe Handling a Time Consuming Initialization

This recipe addresses a common case of needing to run a time-consuming initialization when an application starts. Initially, the layout is set to show a specific Loading splash screen specified in the loading.xml file. In this example, it is a simple text message as shown in Listing 3.8, but it could be a company logo or introductory animation. < xml version 1.0 encoding utf-8 > < TextView android id +id loading android text Loading > While this layout is being displayed, the function...

Recipe Declaring and Enforcing Permissions

Permissions can be assigned to activities, broadcast receivers, content providers, and serv-ices.To assign a permission, the permission element needs to be declared in the desired Android component in the AndroidManifest XML file. For example < permission android name com.myapp android label my app android description using my app > This provides a method not only to specify the permission needed, but also the level of access with the protectionLevel attribute.There are four levels of...

Recipe Launching an Activity for a Result Using Speech to Text

In this recipe, launching an activity for a result is demonstrated. It also demonstrates how to utilize speech to text functionality from Google's Recognizerlntent and print the result to the screen. Here, the trigger event is a button press. It launches the Recognizerlntent activity, which does speech recognition on sound from the microphone and converts it into text.When finished, the text is passed back to the calling activity. Upon return, the onActivityResult() function is first called...

Recipe Using Radio Buttons

A radio button is like a checkbox that cannot be unchecked. Selecting one radio button unselects a previously selected one. Usually a group of radio buttons is put into a RadioGroup view group that ensures only one button of the collection is selected at a time.This is shown in the layout file in Listing 4.18. Figure 4.13 ToggleButton example with unselected and selected widgets. Figure 4.13 ToggleButton example with unselected and selected widgets. < xml version 1.0 encoding utf-8 > <...

Android Application Overview

An Android application consists of various functionalities. Some examples are editing a note, playing a music file, ringing an alarm, or opening a phone contact. These functionalities can be classified into four different Android components, shown in Table 2.1, each of which is specified by a Java base class. Table 2.1 The Four Possible Components of an Android Application Focused thing a user can do Background process Receive messages Store and retrieve data Edit a note, play a game Play...

Location Based Services Listing 108 Android Manifestxml

lt xml version 1.0 encoding utf-8 gt lt manifest android versionCode 1 android versionName 1.0 gt lt application lt activity lt intent-filter gt lt action MAIN gt lt category gt lt intent-filter gt lt activity gt lt uses-sdk android minSdkVersion 4 gt lt uses-permission gt lt uses-permission Second, the layout XML file needs the proper MapView declared to show the Google Map, as shown in Listing 10.9. It can also declare whether the user can interact with the map by declaring the clickable...

The Dichotomy of Android

Android has some interesting dichotomies. Knowing about them upfront is useful not only in understanding what Android is, but what it is not. Android is an embedded OS that relies on the Linux kernel for core system services, but it is not embedded Linux. For example, standard Linux utilities such as X-windows and GNU C libraries are not supported.Writing applications for Android utilizes the Java framework, but it is not Java. Standard Java libraries such as Swing are not supported. Other...

Recipe Using Device Vibration

Device vibration is a common feature in all cellular phones.To control vibration on an Android device, a permission must be defined in the AndroidManifest XML file lt uses-permission gt Then, using the device vibrator is just another Android system service provided by the framework. It can be accessed using the Vibrator class Vibrator myVib Vibrator With a Vibrator instance, just call the vibrate method to start device vibration myVib.vibrate 3000 vibrate for 3 seconds If needed, the cancel...

Views and View Groups

The basic building block of a graphical layout is a view. Each view is described by a View Object, which is responsible for drawing a rectangular area and handling events in that area.The View is a base class for objects that interact with the user they are called widgets. Examples of widgets are buttons and check boxes. A ViewGroup Object is a type of View that acts as a container to hold multiple Views or other ViewGroups . For example, a ViewGroup can hold a vertical or horizontal placement...

Recipe Forcing Single Task Mode

As an application is navigated away from and launched again, it can lead to multiple instances of the activity on the device. Eventually the redundant instance of the activity is killed to free up memory, but in the meantime, it can lead to odd situations. To avoid these, the developer can control this behavior for each activity in the AndroidManifest. To ensure only one instance of the activity runs on the device, specify the following in an activity element that has the main and launcher...

Recipe Passing Primitive Data Types Between Activities

Sometimes data needs to be passed to a launched activity. Sometimes a launched activity creates data that needs to be passed back to the calling activity. For example, a final score of a game needs to be returned to a high-scores screen.The different ways to pass information between activities are Declare the relevant variable in the calling activity for example, public int finalScore and set it in the launched activity for example, CallingActivity.finalScore score . Attach extras onto Bundles...

Resource Directories and General Attributes

The UI display utilizes developer-generated resource files, some of which are discussed in Chapter 2,Application Basics Activities and Intents, in the context of the directory structure of an Android project. For completeness, the entire set of resource directories is summarized here res anim Frame-by-frame animation or tweened animation objects. res drawable Image resources. Note these images can be modified and optimized during compilation. res layout eXtensible Markup Language XML files...

Android System Debug Tools

Android is built on top of Linux, so many Linux tools can be leveraged. For example, to show the applications currently running and the resources they are using, the top command can be used. The following command can be issued at the command line when a device is connected to a host computer through USB cable or the emulator is running An example output from this command is shown in Figure 12.9. The top command also shows the percentage of CPU and memory used in the overall system. Another...

Recipe Using the Temperature and Light Sensor

The temperature sensor is used to determine temperature of the phone for internal hardware calibration. The light sensor measures ambient light and is used to automatically adjust the brightness of the screen. These sensors are not available on all phones, but if they exist, the developer can use them for alternative reasons.The code to read the values from these sensors is shown in Listing 7.6. It can be added to the activity in the previous recipe to see the result. Listing 7.6 Example Code...

Figure 122 The DDMS Control Panel

Inside the DDMS are four panels that provide different kinds of debugging data Devices Displays the connected Android devices including emulators and actual Android devices. Emulator Control Provides multiple controls for injecting events and data into the emulator such as Telephony Status,Telephony Action, and Location Control The Telephony Status specifies the voice and data format, network speed, and latency. The Telephony Actions provides a way to make a fake voice phone call or Short...

Recipe Changing the UI Based on Stored Data

The DataStorage activity of the previous recipe can be extended to check the shared preferences when loading, altering the behavior accordingly. In this recipe, if a username and password is already saved in the SharedPreferences file, a login page is displayed. After a successful login, the activity can successfully continue. If no login information is on file, the activity continues directly. The main.xml layout file can be modified to be a login page, as shown in Listing 9.5. This uses two...

Recipe Using Gestures

A gesture is a hand-drawn shape on a touch screen.The android.gesture package provides libraries to recognize and handle these in a simple way. First, every SDK has a sample program that can be used to build a collection of gestures in The Gesture Builder project can be imported and run on an Android device. It produces a file called sdcard gestures, which can be copied off of the device and used as a raw resource for this recipe. As an example, a file of handwritten numbers can be generated as...

Recipe Dialing a Phone Number

To make a phone call from an application, the following permission needs to be added to the AndroidManifest XML file The act of making a call can either use the ACTION_CALL or action_dialer implicit intent.When using the action_dialer intent, the phone dialer user interface is displayed with the specified phone number ready to call. This is created using startActivity new Intent Intent.ACTION_CALL, When using the ACTION_CALL intent, the phone dialer is not shown and the specified phone number...

Listing 1113 Android Manifestxml

lt manifest android versionCode 1 android versionName 1.0 gt lt uses-sdk lt application lt category gt lt intent-filter gt lt activity gt lt application gt lt manifest gt Anytime the application triggers a backup or restore to the BackupManager, it initiates with the identified backup agent. For example, with the main activity excerpt as follows public class MyBandRActivity extends Activity BackupManager mBackupManager Override public void onCreate Bundle savedInstanceState super.onCreate...

Recipe Reacting to Touch Events

Any interaction with the screen, be it a touch or a navigated selection using the trackball, is an interaction with the corresponding view at that location. Because the screen layout is a hierarchy of views, as described in Chapter 4, the system starts at the top of this hierarchy and passes the event down the tree until it is handled by a view. Some events, if not consumed, can continue to pass down the tree after being handled. Listing 5.9 shows a button called ex_button that handles both a...

SQLite Database

For more complex data structures, a database provides a quicker and more flexible access method than flat files or shared preferences.Android provides a built-in database called SQLite that provides full relational database capability utilizing SQL commands. Each application that uses SQLite has its own instance of the database, which is by default accessible only from the application itself. The database is stored in the data data lt package_name gt databases folder of an Android device.A...

Recipe Setting and Changing Text Attributes

This recipe changes the color of displayed text when a button is clicked. It can easily be extended to change the font size or style instead, as discussed at the end of this recipe. The main layout is simply a TextView and Button arranged in a vertical LinearLayout, as shown in Listing 4.8.The text is identified as mod_text and displays the string changed_text defined in the strings.xml file, as shown in Listing 4.9.The button is identified as change and displays the string button_text from the...

Adding a Broadcast Receiver

A broadcast receiver listens for relevant broadcast messages to trigger an event. Some examples of broadcasted events already sent from the OS are The camera button was pressed. A new application was installed. A user-generated component can also send a broadcast, such as A calculation was finished. A particular thread has started. All broadcast receivers extend the abstract class BroadcastReceiver or one of its subclasses. The lifecycle of a broadcast receiver is simple. A single method,...

Recipe Building Menus

Linearlayout Hide

A developer can implement three types of menus in Android, and this recipe creates an example of each Options menu The main menu for an Activity that displays when the MENU key is pressed. It contains an Icon menu and possibly an Expanded menu when the More menu item is selected. Context Menu A floating list of menu items that displays when a view is long pressed. Submenu A floating list of menu items that displays when a menu item is pressed. The Options menu is created the first time the MENU...

Listing 1010 srccomcookbookusinggmapsMyLocationjava

Import android.content.Context import android.location.Criteria import android.location.Location import android.location.LocationManager import android.os.Bundle import android.widget.TextView import com.google.android.maps.MapActivity import com.google.android.maps.MapView public class MyLocation extends MapActivity LocationManager mLocationManager Location mLocation TextView tv public void onCreate Bundle savedInstanceState super.onCreate savedInstanceState MapView mapView MapView...

Recipe Translating a Location to Address Reverse Geocoding

The Geocoder class provides a method to translate from an address into a latitude-longitude coordinate geocoding and from a latitude-longitude coordinate into an address reverse geocoding . Reverse geocoding might produce only a partial address, such as city and postal code, depending on the level of detail available to the location provider. This recipe uses reverse geocoding to get an address from the device's location and display to the screen, as shown in Figure 10.2.The Geocoder instance...

Recipe Using an Alert Dialog

Providing a user with an alert and up to three buttons of possible actions can be done with the AlertDialog class. Some examples are Your final score was 80 100 Try this level again, advance to next level, or go back to the main menu. The image file is corrupt, choose another or cancel action. This recipe takes the first example and shows how to provide an action on each choice depending on which button is clicked.The example code is shown in Listing 3.20. The AlertDialog is initialized using...

Installing and Upgrading

There are many places on the Internet that discuss detailed step-by-step instructions on how to install the Android SDK. For example, all the necessary links can be found on the Google website the general procedure outlined here serves to emphasize the most common installation steps for reference. These steps should be done on a host computer used as the development environment. 1. Install the Java Development Kit for example, install JDK 6.0 for use with Android 2.1 or above JDK 5.0 is the...

Messages Between Threads Handlers

After multiple threads run concurrently, such as a main application thread and a background thread, there needs to be a way to communicate between them. Some examples are A main thread serves time-critical information and passes messages to the background time-consuming thread to update. A large computation completes and sends a message back to the calling thread with the result. This can be accomplished with handlers, which are objects for sending messages between threads. Each handler is...

Recipe Creating a Custom Content Provider

After getting a sense of how to use a content provider, it is time to integrate one into the diary project used in previous recipes.This recipe shows how to expose diary entries to other selected applications.A custom content provider just extends the Android ContentProvider class, which contains six methods to optionally override query Allows third-party applications to retrieve content. insert Allows third-party applications to insert content. update Allows third-party applications to update...

Recipe Utilizing the Telephony Manager

The telephony API has a TelephonyManager class, which is an Android system service, to access information about the telephony services on the device. Some of the telephony information is permission protected, so access must be declared in the AndroidManifest XML file lt uses-permission gt The main activity is shown in Listing 7.7. Listing 7.7 package com.cookbook.hardware.telephony import android.app.Activity import android.os.Bundle import android.telephony.TelephonyManager import...

Android Native Components

When a computationally intensive function is critical to an Android application, it might be worthwhile to move the intensive computation to native C or C for efficiency. The Android NDK exists to help in the development of a native component.The NDK is a companion to the Android Software Development Kit SDK and includes a bundle of libraries that can be used to build C C libraries. Steps to set up and build an Android native component are 1. Download the Android NDK from http...

Using Web Content

To launch an Internet browser to display web content, the implicit intent action_view can be used as discussed in Chapter 2,Application Basics Activities and Intents, for example Intent i new Intent Intent.ACTION_VIEW It is also possible for developers to create their own web browser by using Webview, which is a View that displays web content.As with any view, it can occupy the full screen or only a portion of the layout in an activity. Webview uses WebKit, the open source browser engine used...

Recipe Sharing a Thread Between Two Applications

The previous recipes motivated the use of multiple threads in a single application.The converse case is also sometimes useful use of multiple applications in a single thread. For example, if two applications need to communicate between each other, they can do so using binders rather than the more complicated inter-process communication IPC pro-tocol.The steps are 1. Make sure each application, when packaged for release, is signed with the same key for security reasons. 2. Make sure each...

Recipe Discovering Bluetooth Devices

After Bluetooth is activated, to discover paired or available Bluetooth devices, use the BluetoothAdapter instance's startdiscovery method as an asynchronous call.This requires registering a BroadcastReceiver to listen for ACTION_FOUND events that tell the application whenever a new remote Bluetooth device is discovered. This is shown in the example code in Listing 7.10. Listing 7.10 Example Code for Discovering Bluetooth Devices private final BroadcastReceiver mReceiver new BroadcastReceiver...

Recipe Autosend an SMS Based on a Received SMS

Because most SMS messages are not read by the recipient until hours later, this recipe sends an autoresponse SMS when an SMS is received. This is done by creating an Android service in the background that can receive incoming SMS. An alternative method is to register a broadcast receiver in the AndroidManifest XML file. The application must declare permission to send and receive SMS in the AndroidManifest XML file, as shown in Listing 8.1. It also declares a main activity SMSResponder that...

Index

Accelerometers, 9 accept method, 188 ACCESS_COARSE_LOCATION permission, 252 ACCESS_FINE_LOCATION permission, 252 accessing camera, 169 content providers, 244 wireless networks, 191-193 ACTION_CALL implicit intent, 185 ACTION_DIALER implicit intent, 185 ACTION_DOWN event, 133 ACTION_MOVE event, 133 ACTION_POINTER_DOWN event, 133 ACTION_POINTER_UP event, 133 ACTION_UP event, 133 active-matrix organic LED displays AudioExamples, 155-157 AudioExamplesRaw, 161-163 AudioExamplesSP, 164...

Recipe Creating a Drop Down Menu

A drop-down menu is called a spinner. It is a widget defined in a normal screen layout such as the one shown in Listing 4.19. lt xml version 1.0 encoding utf-8 gt lt LinearLayout lt Spinner android id id spinner gt The title of the drop-down menu can be specified with the android prompt attribute. It needs to be defined in a strings.xml file, for example lt string name ocean_prompt gt Choose your favorite ocean lt string gt The spinner also needs a separate layout defined for the drop-down menu...

Recipe Starting a Service When the Camera Button Is Pressed

This recipe shows how to start a service based on a broadcasted event, such as when the camera button is pressed. The broadcast receiver is needed to listen for the specified event s and subsequently launch the service.The broadcast receiver itself is started in another component. Here, it is implemented as a standalone activity, SimpleActivity. The activity shown in Listing 3.14 sets up a broadcast receiver and sets up an intent with the filter for the camera button. The filter for...

Recipe Using Check Boxes and Toggle Buttons

Check boxes have a predetermined checkmark graphic, colors for selection, and colors for behavior when pressed.This provides a unifying look and feel across Android applications. However, if a custom graphic to denote selection is required, the setButtonDrawable method can be used. Sticking with the check box example here, the CheckBox widget needs to be declared in a layout file, as shown in Listing 4.16.The android text attribute displays as a label after the checkbox. For illustration, a few...

Recipe Listening for Fling Gestures

As discussed in the beginning of the chapter, each view has an onTouchEvent method associated with it. In this recipe, it is overridden with a gesture detector that sets a gesture listener.The possible gestures in the OnGestureListener interface are onDown Notifies when a tap down event occurs onFling Notifies when a tap down, movement, and matching up event occurs onLongPress Notifies when a long press occurs onScroll Notifies when a scroll occurs onShowPress Notifies when a tap down occurs...

Recipe Creating a Runnable Activity

This recipe is an activity that evaluates a computationally intensive function, such as edge detection in an image. Here, a dummy function called detectEdges is run to emulate the actual image-processing algorithm. If detectEdges is called in onCreate by itself, it hangs the main thread and does not display the UI layout until computation is done. Therefore, a separate thread needs to be created and started for the time-consuming function. Because the main purpose of the activity is this...

Recipe Using Image Buttons in a Table Layout

Android Scaletype

Buttons were introduced in Chapter 2. Like any view, a background image can be added to a button using the android background attribute. However, using the special ImageButton widget provides some additional layout flexibility. It specifies an image using the android src attribute as follows When used in this way, the image shows on top of a button widget.The ImageButton inherits image placement from the ImageView widget using android scaleType. Possible values and how they modify a given image...

Listing 121 srccomcookbookandroiddebugtraceviewtestfactorialjava

Package import android.app.Activity import android.os.Bundle import android.os.Debug public class testfactorial extends Activity public final String tag testfactorial public void onCreate Bundle savedInstanceState super.onCreate savedInstanceState setContentView R.layout.main factorial 10 int result 1 for int i 1 i lt n i result i The factorial method contains two calls to the Debug class the trace is started in a file called testfactorial.trace when the startMethodTracing is called.When the...

Recipe Drawing 3D Images

Android supports the Open Graphics Library for Embedded Systems OpenGL ES .This recipe, based on an Android API Demo, shows how to create a three-dimensional pyramid shape using this library and have it bounce around the screen and spin as it reflects off the edges. The main activity requires two separate support classes one to define the shape shown in Listing 5.17 and one to render the shape shown in Listing 5.18. Listing 5.17 import java.nio.ByteBuffer import java.nio.ByteOrder import...

Recipe Adding a EULA

As discussed in Chapter 1,Overview of Android, it is often useful to have an End User License Agreement EULA display when a user first installs and runs an app. If the user does not accept it, the downloaded application does not run. After a user does accept it, the EULA is never shown again. This EULA functionality is already implemented and available publicly under the Apache License as the Eula class shown in Listing 9.7. It uses SharedPreferences with the boolean preference_eula_accepted to...

Event Handlers and Event Listeners

Most user interaction with an Android device is captured by the system and sent to a corresponding callback method. For example, if the physical Back button is pressed, the onBackPressed method is called.These events can be handled by extending the class and overriding the methods, called event handlers. User interaction with View or ViewGroup objects can also support event listeners.These are methods that wait for the registered event and then trigger the system to send the event information...

The Evolution of Android

Google, seeing a large growth of Internet use and search in mobile devices, acquired Android, Inc., in 2005 to focus its development on a mobile device platform. Apple introduced the iPhone in 2007 with some ground-breaking ideas including multitouch and an open market for applications. Android was quickly adapted to include these features and to offer definite distinctions, such as more control for developers and multitasking. In addition, Android incorporates enterprise requirements, such as...

Recipe Using Toast to Show a Brief Message on the Screen

The Toast method has been introduced in the previous chapter in a compact form Toast.makeText this, text, Toast.LENGTH_SHORT .show It can also be written as a multiline command Toast tst Toast.makeText this, text, Toast.LENGTH_SHORT tst.show This form is useful when the text needs to be shown multiple times, as the instance in the first line can be reused. Two other uses for the multiline Toast command are to reposition the text location or to add an image. To reposition the text location, or...

Data Storage Methods

Complicated and robust Android applications often need to utilize some type of data storage. Depending on the situation, different data storage methods are available to the developer Shared Preferences for lightweight usage, such as saving application settings and the user interface UI state A built-in SQLite database for more complicated usage, such as saving application records The standard Java flat file storage methods InputFileStream and OutputFileStream These are discussed in this...

Recipe Creating a Self Contained Service

The steps to create a self-contained service associated with a single component are 1. Create a class to extend Service. In Eclipse, this can be done by right-clicking the project, choosing New Class and specifying android.app.Service as the super class. 2. Declare the service in the AndroidManifest.xml file by adding a variation of the following this should be done automatically with the previous Eclipse step lt service 3. Override the onCreate and onDestroy methods. In Eclipse, this can be...

Android Inter Process Communication

If two applications need to share resources but cannot get granted permissions, it is possible to define an inter-process communication IPC message. To support IPC, an interface is needed to serve as a bridge between applications.This is provided by the Android Interface Definition Language AIDL . Defining AIDL is similar to a Java interface. In fact, it can be easily done in Eclipse by creating a new Java interface, and after the definitions are complete, changing the suffix of the file from...

Recipe Getting a Devices Rotational Attitude

Ideally, the accelerometer measures the Earth's gravitational field as G 9.8 meters sec2, and the magnetometer measures the Earth's magnetic field that ranges from H 30 T to 60 T depending on the location in the world. These two vectors are enough to implement a simple textbook estimation of rotation, as used in the getRotationMatrix method. This recipe shows how to use this information. The coordinate system of the device also known as the body frame is defined as x-axis in the direction of...

Android Backup Manager

In Android devices, end users store a lot of data on different applications like notes, game data, application settings, address book entries, and so on.All these data cannot be recovered after they are gone. In the past, developers needed to find alternative ways to back up application data to a remote server.With the introduction of Android 2.2, the support for an Android backup service hosted by Google was introduced. All the application data can use the backup service to store any data to...

Maintaining Forward Compatibility

New Android versions are generally additive and forward compatible at the API level. In fact, a device can be called an Android device only if it passes compatibly tests with the Android APIs. However, if an application makes changes to the underlying system, compatibility is not guaranteed.To ensure forward compatibility of an application when future Android updates are installed on devices, follow these rules suggested by Google Do not use internal or unsupported APIs. Do not directly...

Recipe Recording Audio Files

Recording audio using MediaRecorder is similar to playback from the previous recipe, except a few more things need to be specified note, default can also be used and is the same as the first choice in these lists voice_uplink Transmitted audio during voice call voice_downlink Received audio during voice call V0ICE_CALL Both uplink and downlink audio during voice call camcorder Microphone associated with camera if available tuned for voice recognition if available three_GPP 3GPP media file...

Recipe Using a Progress

This recipe demonstrates the usage of a progress bar by taking Listing 4.7 from Recipe Updating a Layout from a Separate Thread, which used text to show progress in a computation, and it shows the progress graphically instead. This is done by adding a progress bar object to the layout, such as lt ProgressBar android layout_width 270px android layout_height 50px android progress 0 android secondaryProgress 0 gt As the progress changes, the android progress attribute can change to show a bright...

Recipe Using Log Cat

Logcat is the real-time logging tool Android provides. It collects all system and application log data in circular buffers, which can then be viewed and filtered. It can be accessed as a standalone tool or as part of the DDMS tool. LogCat can be used in the device after executing the adb shell to log into the device or by using the logcat command through the adb gt adb logcat lt option gt lt filter-spec gt All the messages that utilize the android.util.Log class have an associated tag and...

Recipe Opening a Bluetooth Socket

To establish a Bluetooth connection with another device, the application needs to implement either the client-side or server-side socket. After the server and client are bonded, there is a connected Bluetooth socket for each device on the same RFCOMM Bluetooth transport protocol . However, the client device and service device obtain the Bluetooth socket in different ways.The server receives the Bluetooth socket instance when an incoming connection is accepted. The client receives the instance...

Recipe Loading an Image for Manipulation

This recipe shows an example of an image cut into four pieces and scrambled before being displayed to the screen. It also shows how to create a selectable list of images. When a picture is taken on the device, it is put in the DCIM Camera directory, which is used as an example image directory in this recipe. The image directory is passed to the ListFiles activity, which lists all files and returns the one chosen by the user. The chosen picture is then loaded into memory for manipulation. If the...

Recipe Choosing and Playing Back Audio Files

The MediaRecorder and MediaPlayer classes are used to record and play back either audio or video. This recipe focuses on audio, and the usage is straightforward. For playback, the steps are 1. Create an instance of the MediaPlayer MediaPlayer m_mediaPlayer new MediaPlayer 2. Specify the source of media. It can be created from a raw resource m_mediaPlayer MediaPlayer.create this, R.raw.my_music Another option is to set as a file from the filesystem which then also needs a prepare statement...

Recipe Utilizing the SEARCH

If an activity in the in-focus application is defined to be searchable, the SEARCH key invokes it. A menu choice or equivalent should always be a redundant way to call the searchable activity to accommodate devices without a SEARCH key. The menu choice simply needs a call to onSearchRequested . The searchable activity ideally should be declared as singleTop launch mode, as discussed in Chapter 2,Application Basics Activities and Intents.This enables multiple searches to take place without...

Recipe Creating an App Widget

This recipe creates a simple App Widget that displays some text on the home screen. The text is configured to update every second, but note that by default, the Android system forces the minimum update time to be 30 minutes.This helps avoid poorly written widgets from draining the battery. Listing 3.17 implements an AppWidgetProvider, which is a subclass of BroadcastReceiver.The main method to override is the onUpdate function, which gets called when the system determines it is time to update...

Recipe Using a Seek Bar

Android Custom Seekbar

A seek bar is similar to a progress bar that can take user input to change the amount of progress. Current progress is indicated by a small sliding box called a thumb. A user can click and drag the thumb to visually indicate the new place to set the progress.The main activity is shown in Listing 4.23. Listing 4.23 import android.app.Activity import android.os.Bundle import android.widget.SeekBar public class SeekBarEx extends Activity public void onCreate Bundle savedInstanceState...

Sensors

Smartphones are becoming sensor hubs in a way, opening a rich experience for users. Other than the microphone that every phone has, the first additional sensor introduced on phones was the camera. Different phone cameras have varying capabilities, and this is an important factor for people in selecting a device.The same type of diversity is now seen with the additional sensors. Most smartphones have at least three basic sensors a three-axis accelerometer to measure gravity, a three-axis...

Recipe Using Sound Resources Efficiently

To keep the smaller memory requirements of compressed audio files but also the benefit of lower-latency playback of raw audio files, the SoundPool class can be used.This uses the MediaPlayer service to decode audio and provides methods to repeat sound buffers and also speed them up or slow them down. Usage is similar to other sound recipes initialize, load a resource, play, and release. However, note that the SoundPool launches a background thread, so a play right after a load might not produce...

Recipe Scheduling a Runnable Task from the Main Thread

This recipe implements a clock timer, which is often needed in applications. For example, it can be used in a game to keep track of how long a player takes to complete a level. This provides a simple way to handle user interaction while a background thread continues to run. The timer is run in a background thread so it does not block the UI thread, but it needs to update the UI whenever the time changes.As shown in Listing 3.5, the TextView text starts with a welcome message and the button text...

Recipe Listening for Phone States

The PhoneStateListener class provides information about the different telephony states on the device, including network service state, signal strength, and message waiting indicator voicemail . Some require an explicit permission as shown in Table 7.2. Table 7.2 The Possible Phone State Listener Events and Required Permissions LISTEN_CELL_LOCATION LISTEN_DATA_ACTIVITY Listen for call forward indicator changes Listen for direction of data traffic on cellular changes Listen for data connection...

Listing 917 srccomcookbookdatastorageDisplay Diariesjava

Import java.text.DateFormat import java.util.ArrayList import java.util.Date import android.content.Context import android.database.Cursor import android.view.ViewGroup import android.widget.BaseAdapter import com.cookbook.data.Constants import com.cookbook.data.MyDB public class DisplayDiaries extends ListActivity MyDB dba DiaryAdapter myAdapter private class MyDiary public MyDiary String t, String c, String r title t content c recorddate r public String title public String content public...

Recipe Using Implicit Intents for Creating an Activity

Implicit intents do not specify an exact component to use. Instead, they specify the functionality required through a filter, and the Android system must determine the best component to utilize. An intent filter can be either an action, data, or a category. The most commonly used intent filter is an action, and the most common action is ACTION_VIEW.This mode requires a uniform resource identifier URI to be specified and then displays the data to the user. It does the most reasonable action for...

Recipe Using a Countdown Timer

The previous recipe is an example of handlers and a functional timer.Another timer is provided with the built-in class CountDownTimer.This encapsulates the creation of a background thread and the handler queuing into a convenient class call. The countdown timer takes two arguments the number of milliseconds until the countdown is done and how often in milliseconds to process onTick callbacks.The onTick method is used to update the countdown text. Note that otherwise the recipe is identical to...

Recipe Creating a Form

A form is a graphical layout with areas that can take text input or selection. For text input, an EditText object can be used.After it is declared, some Java code needs to capture the text entry at run-time.This is done as shown in Listing 4.14. Note that the content of the text entry textResult in this example should not be modified.A copy of the content can be made in case modification is needed. Listing 4.14 Capturing Text from an EditText Object EditText textResult EditText findViewById...

Threads

BAD USAGE function call to time-consuming function causes main thread to hang Figure 3.1 An example of the message that displays when a thread hangs. Figure 3.1 An example of the message that displays when a thread hangs. This means any user request such as navigating back to the home screen or multiple pushes of an onscreen button are not registered until the music is completely finished playing. The unresponsive UI might even cause the Android system to show an error such as the previous one...

Recipe Using an Http Get

Besides launching a browser or using the Webview widget to include a WebKit-based browser control in an activity, developers might also want to create native Internet-based applications. This means the application relies on only the raw data from the Internet, such as images, media files, and XML data. Just the data of relevance can be loaded.This is important for creating social networking applications.Two packages are useful in Android to handle network communication java.net and android.net....

Recipe Manipulating Raw Audio

The MediaRecorder MediaPlayer framework is useful for most audio uses, but to manipulate raw audio straight from the microphone, process it without saving to a file, and or play back raw audio, use AudioRecord AudioTrack instead. First, set the permission in the AndroidManifest XML file lt uses-permission gt Then, the steps to record are 1. Create an AudioRecord instance, specifying the following to the constructor Audio source Use one of the MediaRecorder.AudioSource choices described in the...

Recipe Adding Markers on a

The itemizedOverlay class provides a way to draw markers and layovers on top of a MapView. It manages a set of OverlayItem elements, such as an image, in a list and handles the drawing, placement, click handling, focus control, and layout optimization for each element. Create a class that extends ItemizedOverlay and override the following addOverlay Adds an Overlayltem to the ArrayList.This calls populate , which reads the item and prepares it to be drawn. createItem Called by populate to...

Recipe Using Multitouch

A multitouch event is when more than one pointer such as a finger touches the screen at the same time. This is identified by using a touch listener OnTouchListener, which receives multiple types of motion events action_down A press gesture has started with a primary pointer finger . action_pointer_down A secondary pointer finger has gone down. action_move A change in press location has changed during a press gesture. action_pointer_up A secondary pointer was released. action_up A primary...