Creating a Wallpaper Service Engine
The WallpaperService.Engine class is where you create the Live Wallpaper itself. The Wallpaper Service Engine encapsulates a Surface which is used to display the wallpaper and handle touch events. A Surface is a specialized drawing canvas that supports updates from background threads, making it ideal for creating smooth, dynamic, and interactive graphics. Both the Surface View, and handling touch events, are covered in more detail in Chapter 15. To implement your own Wallpaper Service engine,...
Playing Video Using the Video View
The simplest way to play back video is to use the VideoView control. The Video View includes a Surface on which the video is displayed and encapsulates and manages a Media Player to manage the video playback. The Video View supports the playback of local or streaming video as supported by the Media Player component. Video Views conveniently encapsulate the initialization of the Media Player. To assign a video to play, simply call setVideoPath or setVideoUri to specify the path to a local file,...
Checkable menu items
Any menu item can be used as an interface for turning options on and off. This can be indicated with a checkbox for stand-alone options, or radio buttons for groups of mutually exlusive options see the screenshot, to the right . Note Menu items in the Icon Menu cannot display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, then you must personally indicate the state by swapping the icon and or text each time the state changes between on and off. To make a...
Canvas Drawing
Now that we've explored how widgets allocate the space on the screen in which they draw themselves, we can turn to coding some widgets that actually do some drawing. The Android framework handles drawing in a way that should be familiar, now that you've read about measurement and arrangement. When some part of the application determines that the current screen drawing is stale because some state has changed, it calls the View method invalidate. This call causes a redraw event to be added to the...
x8632 cont
chmod x release-sourceforge android pxa270 scripts bin mkimage Setup Compiling Options This step _could be ignored _ make menuconfig under release-sourceforge android-pxa270 directory Please enter a string value, use the lt TAB gt key to move from the input field to the buttons below it. -i686-pc - linux-gnu. tar, bz2 riux-2 . 6 . 25-androld-l, a rl Android 1.6 SDK, Release Use our pre-build Android root file system directly Compile from our modified Android source code Do you wishjv o save...
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...
Image Capture Using the BuiltIn Camera Application
With mobile phones quickly becoming mobile computers, they have in many ways replaced a whole variety of consumer electronics. One of the earliest non-phone related hardware capabilities added to mobile phones was a camera. Currently, it seems someone would be hard pressed to buy a mobile phone that doesn't include a camera. Of course, Android-based phones are no exception from the beginning, the Android SDK has supported accessing the built-in hardware camera on phones to capture images. The...
Testing the Scripts
Save the scripts in Listings 1-2 and 1-3 as agcc and ald in your HOME bin directory. Then issue the following commands to test them arm-none-linux-gnueabi-gcc Sourcery G Lite 2008q3-72 4.3.2 Copyright C 2008 Free Software Foundation, Inc. This is free software see the source for copying conditions. There is NO warranty not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. arm-none-linux-gnueabi-ld warning library search path is unsafe for cross-compilation GNU ld Sourcery G Lite...
Inserting Media into the Media Store
Rather than relying on the Media Scanner you can add new media to the Media Store by creating a new ContentValues object and inserting it into the appropriate Media Store Content Provider yourself. The metadata you specify here can include the title, time stamp, and geocoding information for your new media file, as shown in the code snippet below ContentValues content new ContentValues 3 content.put Audio.AudioColumns.TITLE, TheSoundandtheFury System.currentTimeMillisO 1000 content.put...
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...
Drawing on Existing Images
Since we are drawing on a Canvas, we can use techniques described in the previous chapter to draw an image to the Canvas and then draw on top of that image. package import java.io.FileNotFoundException import android.app.Activity import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color import android.graphics.Matrix import android.graphics.Paint import android.net.Uri import android.os.Bundle...
Create New Documents
Documents To Go Full gives you the ability to create new Microsoft Word, Excel and PowerPoint documents on your device. Your newly created documents can be synchronized back to your desktop after your next synchronization or saved locally on your device only. To create a new document, press the Menu button, then choose Create New Document OR press the softkey at the bottom of the screen. Note By default, the new documents you create will be in Microsoft Office 97-2004 e.g., .doc, .xls, .ppt ....
Network Video Playback
Android supports HTTP and RTSP video playback in all three video playback methods discussed in Chapter 9. Using either the built-in Media Player activity via an intent or the VideoView class to play either form of network video requires no source code changes. Simply use the HTTP or RTSP URL as the video Uri, and it will work as long as the format is supported. Here is the ViewTheVideo activity example from Chapter 9 that uses a VideoView with an RTSP URL to a video from YouTube's mobile site....
Linkify Demo
This technique should work for demos that you can't find with the previous method. If the ApiDemos application doesn't store information about the demo in res strings.xml, it gets its information directly from AndroidManifest.xml and so will we. 1. After starting the ApiDemos application, find the particular demo through clicking on the menu, and remember the path you took through the menu system. In this case, you click on Text and then Linkify. 2. Open the AndroidManifest.xml file and search...
Creating Compound Controls
Compound controls are atomic, reusable Views that contain multiple child controls laid out and wired together. When you create a compound control you define the layout, appearance, and interaction of the Views it contains. You create compound controls by extending a ViewGroup usually a layout . To create a new compound control choose the layout class that's most suitable for positioning the child controls, and extend it as shown in Listing 4-6. LISTING 4-6 Creating a compound control...
Best File Server App
Suppose you are traveling and want to share your files with colleagues but your company email is down. Fire up an FTP server and let your colleagues get whatever you designate for retrieval. Once you set this app up, you simply run the server and it will provide you with a server URL that can be shared , with whomever you want accessing files. Whether you have music files, pictures, documents, or log files, you can make them easily accessible with 42 this app. MINIMALIST DESIGN The design is...
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 srccomcookbookdatastorageDisplayDiariesjava
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...
Installing KiloGap in the Emulator
Now it's time to test our shiny new native Android app in the emulator. 1. If your emulator is not running, launch it by entering the following command in the Terminal application this way, you can let it warm up while you're building the Kilo package You should see the Android emulator window appear after a few seconds. Notice that the command prompt doesn't return in the terminal window it will sort of just sit there and hang until you close the emulator. We won't be interacting with this...
Using LocationManager and LocationProvider
When building location-aware applications on the Android platform, there are several key classes you will use very often. A LocationProvider provides location data using several metrics, and its data is accessed through a LocationManager. LocationManager, along with returning the available providers, also allows you to attach a LocationListener to be updated when the device location changes and or directly fire an Intent based on the proximity to a specified latitude and longitude. The...
Mipmapping
If you've played around with our previous examples and let the cube move further away from the camera, you might have noticed that the texture starts to looks grainy and full of little artifacts the smaller the cube gets. This effect is called aliasing, a prominent effect in all types of signal processing. Figure 11-8 shows you the effect on the right side and the result of applying a technique called mipmapping on the left side. Figure 11-8. Aliasing artifacts on the right the results of...
color value
Value is a color, using web-style syntax, as describe above. Has only one attribute name - The name used in referring to this color. The following code declares two colors, the first fully opaque, and the second translucent. opaque red gt f00 lt color gt translucent red gt 8 0ff0000 lt color gt layout width fill parent layout height wrap content textColor color translucent red
Widget graphics tips and tricks
The Android team has developed a few tricks for aligning widget artwork within standard widget bounding boxes and frames, so the widget aligns visually with other widgets and the other elements of the Home screen, as well as other techniques for creating widgets. Use a screen shot from the Android SDK emulator to align both the shapes and shadows of your widget controls with the Search widget and with other elements on the Home screen. Cut the widget artwork asset based on the full size of a...
Using the Simple Cursor Adapter
The SimpleCursorAdapter lets you bind a Cursor to a List View, using a custom layout definition to define the layout of each row item, which is populated by a row's column values. Construct a Simple Cursor Adapter by passing in the current context, a layout resource, a Cursor, and two arrays one that contains the names of the columns to be used, and a second equally-sized array that has resource IDs for the Views to use to display the contents of the corresponding columns. Listing 5-25 shows...
return trueIntent extra C
intent new Intent this, ReviewCriteria.class startActivity intent return true return super.onMenuItemSelected featureld, item protected void onListItemClick ListView l, View v, D int position, long id lt 1-' RestaurantFinderApplication application RestaurantFinderApplication getApplication Intent intent new Intent Constants . INTENT_ACTION_VIEW_DETAIL getIntent .getIntExtra Constants . STARTFROM_EXTRA, 1 lt 1 startActivity intent Pass startFrom Get Application extra value object and set private...
Including SQLite
Our initial work involves configuring our Xcode project with references to the SQLite library. The first step is to add a new framework to the project. NOTE This process is quite complicated in the Xcode 4 beta that I'm using it's possible that this will be made slightly easier in the production version. Refer to the web site if these steps seem to bear no relation to your edition of Xcode. In the Project Navigator, click on the project entry at the top of the tree. This is the blue box titled...
Controlling and Monitoring Camera Settings and Image Options
The camera settings are stored using a Camera.Parameters object, accessible by calling the getParameters method on the Camera object. In order to modify the camera settings, use the set methods on the Parameters object before calling the Camera'setParameters method and passing in the modified Parameters object. LISTING 11-13 Reading and modifying camera settings Available for download on Camera.Parameters parameters camera.getParameters Wrox.com make changes Android 2.0 API level 5 introduced a...
in Phone mftftXftGallery mm
Android. widget.BaseAdapter gt Android.widget.ImageView ffi ffiftiSi-HBfK ft JttfaZ. BU, 7 ifff H Context widget M BaseAdapter, ft Activity , Context PN Canvas 10 , ITO t S IMo Activity Zi ffitflftMtt, ft31 Intent UkR Context ftUM intent X Android.content TfO Context iil c Jf Ifrfett Layout M M Gallery MM-, Sffiil widget.BaseAdapter Gallery flxW tflM it, Gallery Android DttAlft Icon a IS 3-15 Gallery 40 gt tliME, Mit iSiSM Mjt ImageAdapter Gallery gftffltfftSBSIffl. import android.app.Activity...
Sending Data Messages
You can send binary data via SMS using the sendDataMessage method on an SMS Manager. The sendDataMessage method works much like sendTextMessage, but includes additional parameters for the destination port and an array of bytes that constitutes the data you want to send. Listing 12-18 shows the basic structure of sending a data message. LISTING 12-18 Sending SMS data messages Available for Intent sentIntent new Intent SENT_SMS_ACTION 'wrox comn PendingIntent sentPI byte data your data...
Doom Library DSO Compilation
Listing 7-25 shows the Makefile for the DSO. It uses the compiler and linker helper scripts agcc and ald, created in Chapter 1. The default optimization level is set to 2. Other compilation flags include the following -ffast-math Use fast math. -Wall Display all warnings. -nostdinc Do not include standard header files. lib builds the DSO libdoom_jni.so. jni creates the JNI headers for doom.jni.Natives.java and places them in the include folder. deploy-lib deploys the DSO to the device using the...
Camera Example 1
In this section, we will step through writing an application that will allow you to take pictures using the smartphone camera using PhoneGap APIs on iPhone. Create a new PhoneGap iPhone project, using the steps from the previous examples. Name the project pg_camera. The complete source code to the completed application is available online at Replace the generated index.html file in the www directory with the following lt DOCTYPE HTML PUBLIC - W3C DTD HTML 4.01 EN lt html gt lt head gt lt meta...
Development Architecture
Rhodes applications are installed and run as native applications. However, you develop using the web development paradigm. You define the user interface of your application in HTML and CSS. Then, at runtime, the HTML and CSS is rendered in a native browser UI control that is embedded in your application by the Rhodes framework. JavaScript may be used for some interaction control the same way that you would use JavaScript in a web application. You can also add application logic to your views...
A Brief Tour of the MJAndroid Code
MJAndroid is a relatively simple application, despite the capabilities it gives its users. This section will give you an overview of the code and resource modules, tell you where they are located in the directory structure, and provide a glimpse of what each component does. You may want to refer to this section in the future when you're trying to find example code for a particular function and want to locate it in the MJAndroid code tree. MJAndroid uses a directory structure that is derived...
Downloading the MJAndroid Code
The MJAndroid application source code and project files are available from the O'Reilly website, at To download it to your development system, use a browser to navigate to the link given, and select Download MJAndroid. Your operating system Windows, Linux, or OS X will ask you to confirm that you want the download to happen, and ask you where to put the downloaded files. It doesn't matter where you put the downloaded, compressed files, but you want to extract the uncompressed files into the...
BlackBerry Browser UI Controls
Developing for the BlackBerry web UI requires a disciplined approach to work within the limitations of the target browser. There are two separate browser-rendering engines included on the BlackBerry platform browser.field available since v3.8 with most recent changes made in v4.5 The level of content support provided by this browser is limited to Document Object Model DOM L1 read only access to the DOM . Partial support for HTML, JavaScript and CSS. Content rendered using this browser field...
putExtras and getExtras methods
Flags of various sorts. Many instruct the Android system how to launch an activity for example, which task the activity should belong to and how to treat it after it's launched for example, whether it belongs in the list of recent activities . All these flags are defined in the Intent class. The Android system and the applications that come with the platform employ Intent objects both to send out system-originated broadcasts and to activate system-defined components. To see how to structure an...
Data Data Everywhere
If you are used to developing for other databases, you are also probably used to having tools to inspect and manipulate the contents of the database, beyond merely the database's API. With Android's emulator, you have two main options for this. First, the emulator is supposed to bundle in the sqlite3 console program and makes it available from the adb shell command. Once you are in the emulator's shell, just execute sqlite3, providing it the path to your database file. Your database file can be...
Accessing telephony information
Android provides a very informative manager class that supplies information about many telephony-related details on the device. Using this class, TelephonyManager, you can access many of the GSM SIM properties we have already discussed, and you can obtain phone network state information and updates. Attaching an event listener to the phone, in the form of a PhoneStateListener, which is done via the manager, is how you can make your applications aware of when phone service is and is not...
Transformative Drawables
You can scale and rotate existing Drawable resources using the aptly named ScaleDrawable and RotateDrawable classes. These transformative Drawables are particularly useful for creating progress bars or animating Views. CMlftiiL-.i ne r-d L n y ci u I Re in ui lt i gt gt ScaleDrawable Within the lt scale gt tag, use the scaleHeight and scaleWidth attributes to define the target height and width relative to the bounding box of the original Drawable. Use the scaleGravity attribute to control the...
Sending SMS and MMS from Your Application Using Intents and the Native Client
In many circumstances you may find it easier to pass on the responsibility for sending SMS and MMS messages to another application, rather than implementing a full SMS client within your app. To do so, call startActivity using an Intent with the Intent.ACTION_SENDTO action. Specify a target number using sms schema notation as the Intent data. Include the message you want to send within the Intent payload using an sms_body extra, as shown in Listing 12-13. LISTING 12-13 Sending an SMS message...
Organizing Data with Lists
Lists are one of the most frequently used components in iPhone applications, as they provide a simple way to layout various types of information, and can optionally provide hierarchical organization to allow for sub-lists and navigation. iWebKit provides several different formatting options for lists in your application. You can choose to style your list using the classic style, with support for images and comments a list in the classic iTunes style, containing album covers, artist, title, and...
Exception Handling
What if something goes wrong The code in the call method that starts the dialer is wrapped in a try catch block. The catch statement contains a line of code that logs an error if the startActivity method throws an exception of the type ActivityNot FoundException. If a method can throw an exception that indicates an error, the call to that method should be in a try catch block that catches that type of exception. In this case, we use Android's logging facility to record the error. We do not...
Sencha Touch
Sencha Touch www.sencha.com products touch is a JavaScript framework for creating web applications targeted to touch-based devices. Sencha Touch is the flagship product of Sencha formerly Ext JS , a Palo Alto, Calif. company launched in 2007 that makes application frameworks. Sencha Touch combines ExtJS, jQTouch and Rapha l. Unlike jQTouch, Sencha Touch is not dependent on jQuery and is compatible with both the iPhone and Android. Sencha Touch is distributed under the GPL v3 open source...
Initializing Sprites and Sounds
Game initialization occurs in the initialize method overloaded from the parent abstract class ArcadeGame see Listing 3-6 . The call sequence goes as follows LinearLayout.onLayout calls ArcadeGame.initilize, which calls SpaceBlasterGame.initilize. This last method performs the following tasks Set the style and color attributes for the Paint objects text, laser bar, and shield bar. Load the game bitmap sprites ship, meteor, laser bullet, and explosion sequence. mTextPaint.setARGB 255, 255, 255,...
Extending and Using the Application Class
Listing 3-7 shows the skeleton code for extending the Application class and implementing it as a singleton. LISTING 3-7 Skeleton application class LISTING 3-7 Skeleton application class Wrax.com import android.content.res.Configuration public class MyApplication extends Application private static MyApplication singleton Returns the application instance public static MyApplication getInstance return singleton public final void onCreate super.onCreate singleton this Once created, you must...
Drawing graphics in Android
In this section we are going to be looking at Android's graphical capabilities as well as examples of how to make simple 2D shapes. We will be making use of the android.graphics package see android graphics package-summary.html , which provides all the low-level classes and tooling needed to create graphics. The graphics package supports such things as bitmaps which hold pixels , canvas what your draw calls draw on , primitives such as rectangles or text , and paint which you use to add color...
Using Repeating Alarms to Update Earthquakes
In this final modification to the Earthquake example you'll use Alarms to replace the Timer currently used to schedule Earthquake network refreshes. One of the most significant advantages of this approach is that it allows the Service to stop itself when it has completed a refresh, freeing significant system resources. 1. Start by creating a new EarthquakeAlarmReceiver class that extends BroadcastReceiver. package com.paad.earthquake import android.content.BroadcastReceiver import...
Layer Drawable
A LayerDrawable lets you composite several Drawable resources on top of one another. If you define an array of partially transparent Drawables you can stack them on top of one another to create complex combinations of dynamic shapes and transformations. Similarly, you can use Layer Drawables as the source for the transformative Drawable resources described in the preceding section, or the State List and Level List Drawables that follow. Listing 4-21 shows a Layer Drawable. These are defined via...
The Pool Class Because Reuse is Good for You
What's the worst thing that can happen to us as Android developers World-stopping garbage collection If you look at the Input interface definition in Chapter 3, you'll find the methods getTouchEvents and getKeyEvents . These return lists of TouchEvents and KeyEvents. In our keyboard and touch event handlers, we'll constantly create instances of these two classes and store them in lists internal to the handlers. The Android input system fires a lot of those events when a key is pressed or a...























