Emulator Networking

The emulator provides versatile networking capabilities that you can use to set up complex modeling and testing environments for your application. The sections below introduce the emulator's network architecture and capabilities. Each instance of the emulator runs behind a virtual router firewall service that isolates it from your development machine's network interfaces and settings and from the internet. An emulated device can not see your development machine or other emulator instances on...

Using Resources in Code

Using resources in code is just a matter of knowing the full resource ID and what type of object your resource has been compiled into. Here is the syntax for referring to a resource Where resource_type is the R subclass that holds a specific type of resource. resource_name is the name attribute for resources defined in XML files, or the file name (without the extension) for resources defined by other file types. Each type of resource will be added to a specific R subclass, depending on the type...

How to Avoid ANR

Given the above definition for ANR, let's examine why this can occur in Android applications and how best to structure your application to avoid ANR. Android applications normally run entirely on a single (i.e. main) thread. This means that anything your application is doing in the main thread that takes a long time to complete can trigger the ANR dialog because your application is not giving itself a chance to handle the input event or Intent broadcast. Therefore any method that runs in the...

Calling an IPC Method

Here are the steps a calling class should make to call your remote interface 1. Declare a variable of the interface type that your .aidl file defined. 2. Implement ServiceConnection. 3. Call Context.bindServiceO, passing in your ServiceConnection implementation. 4. In your implementation of ServiceConnection.onServiceConnectedO, you will receive an IBinder instance (called service). Call service) to cast the returned parameter to Yourlnterface type. 5. Call the methods that you defined on your...

Using aapt

Aapt stands for Android Asset Packaging Tool and is included in the tools directory of the SDK. This tool allows you to view, create, and update Zip-compatible archives (zip, jar, apk). It can also compile resources into binary assets. Though you probably won't often use aapt directly, build scripts and IDE plugins can utilize this tool to package the apk file that constitutes an Android application. For more usage details, open a terminal, go to the tools directory, and run the command Linux...

Extending the Content Provider class

You define a ContentProvider subclass to expose your data to others using the conventions expected by ContentResolver and Cursor objects. Principally, this means implementing six abstract methods declared in the ContentProvider class The query() method must return a Cursor object that can iterate over the requested data. Cursor itself is an interface, but Android provides some ready-made Cursor objects that you can use. For example, SQLiteCursor can iterate over data stored in an SQLite...

Implementing IPC Using AIDL

Follow these steps to implement an IPC service using AIDL. 1. Create your .aidl file - This file defines an interface (YourInterface.aidl) that defines the methods and fields available to a client. 2. Add the .aidl file to your makefile - (the ADT Plugin for Eclipse manages this for you). Android includes the compiler, called AIDL, in the tools directory. 3. Implement your interface methods - The AIDL compiler creates an interface in the Java programming language from your AIDL interface. This...

Info

< permission android description string resource android icon drawable resource android label string resource android name string dangerous signature signatureOrSystem > Declares a security permission that can be used to limit access to specific components or features of this or other applications. See the Permissions section in the introduction, and the Security and Permissions document for more information on how permissions work. A user-readable description of the permission, longer and...

Playing from a Raw Resource

Perhaps the most common thing to want to do is play back media (notably sound) within your own applications. Doing this is easy 1. Put the sound (or other media resource) file into the res raw folder of your project, where the Eclipse plugin (or aapt) will find it and make it into a resource that can be referenced from your R class 2. Create an instance of MediaPlayer, referencing that resource using MediaPlayer.create, and then call startO on the instance MediaPlayer mp...

Declaring and Enforcing Permissions

To enforce your own permissions, you must first declare them in your AndroidManifest.xml using one or more < permission> tags. For example, an application that wants to control who can start one of its activities could declare a permission for this operation as follows < manifest package com.me.app.myapp > The < protectionLevel> attribute is required, telling the system how the user is to be informed of applications requiring the permission, or who is allowed to hold that...

Enforcing Permissions in Android Manifestxml

High-level permissions restricting access to entire components of the system or application can be applied through your AndroidManifest.xml. All that this requires is including an android permission attribute on the desired component, naming the permission that will be used to control access to it. Activity permissions (applied to the < activity> tag) restrict who can start the associated activity. The permission is checked during Context.startActivitvO and Activitv.startActivitvForResultO...

Setting hardware emulation options

When are creating a new AVD that uses a standard Android system image (Type platform), the android tool lets you set hardware emulation options for virtual device. The table below lists the options available and the default values, as well as the names of properties that store the emulated hardware options in the AVD's configuration file (the config.ini file in the AVD's local directory). The amount of physical RAM on the device, in megabytes. Default value is 96. Whether there is a touch...

Upgrade the UI to an XML Layout

The Hello, World example you just completed uses what is called a programmatic UI layout. This means that you constructed and built your application's UI directly in source code. If you've done much UI programming, you're probably familiar with how brittle that approach can sometimes be small changes in layout can result in big source-code headaches. It's also very easy to forget to properly connect Views together, which can result in errors in your layout and wasted time debugging your code....

App Widget Configuration UI

Widget hosts have the ability to start a configuration activity when a widget is instantiated. The activity should be declared as normal in AndroidManifest.xml, and it should be listed in the AppWidgetProviderInfo XML file in the android configure attribute. The activity you specified will be launched with the ACTION APPWIDGET CONFIGURE action. See the documentation for that action for more info. See the sample class in ApiDemos for an example.

Creating a Custom Dialog

If you want a customized design for a dialog, you can create your own layout for the dialog window with layout and widget elements. After you've defined your layout, pass the root View object or layout resource ID to setContentView(View). For example, to create the dialog shown to the right 1. Create an XML layout saved as custom_dialog.xml < LinearLayout android id +id layout_root android padding 10dp > < ImageView android id +id image > < TextView android id +id text android...

Showing a Dialog

A dialog is always created and displayed as a part of an Activity. You should normally create dialogs from within your Activity's onCreateDialog(int) callback method. When you use this callback, the Android system automatically manages the state of each dialog and hooks them to the Activity, effectively making it the owner of each dialog. As such, each dialog inherits certain properties from the Activity. For example, when a dialog is open, the Menu key reveals the options menu defined for the...

Define Menus in XML

Just like Android UI layouts, you can define application menus in XML, then inflate them in your menu's onCreate () callback method. This makes your application code cleaner and separates more interface design into XML, which is easier to visualize. To start, create a new folder in your project res directory called menu. This is where you should keep all XML files that define your application menus. In a menu XML layout, there are three valid elements < menu> , < group> and < item>...

Working with Emulator Disk Images

The emulator uses mountable disk images stored on your development machine to simulate flash (or similar) partitions on an actual device. For example, it uses disk image containing an emulator-specific kernel, the Android system, a ramdisk image, and writeable images for user data and simulated SD card. To run properly, the emulator requires access to a specific set of disk image files. By default, the Emulator always looks for the disk images in the private storage area of the AVD in use. If...

Enforcing Permissions when Sending Broadcasts

In addition to the permission enforcing who can send Intents to a registered BroadcastReceiver (as described above), you can also specify a required permission when sending a broadcast. By calling Context.sendBroadcastO with a permission string, you require that a receiver's application must hold that permission in order to receive your broadcast. Note that both a receiver and a broadcaster can require a permission. When this happens, both permission checks must pass for the Intent to be...

TMobile G1 Media Formats

In addition to the core media formats supported in the Android platform, the T-Mobile G1 also supports the formats listed below. L1 64 kbps - 161 kbps 44.1kHz L2 < 161 kbps < 48 kHz L3 < 385 kbps < 48 kHz Mono and stereo profiles with 16-bits per sample. Decoder does not support WMA Pro, Lossless, or Speech codecs. Versions 7, 8 and 9. Simple profile only Limited to baseline profile up to 480x320, and 600 kbps average bitrate for the video stream. Note that Windows Media codecs are not...

Activity lifecycle

An activity has essentially three states It is active or running when it is in the foreground of the screen (at the top of the activity stack for the current task). This is the activity that is the focus for the user's actions. It is paused if it has lost focus but is still visible to the user. That is, another activity lies on top of it and that activity either is transparent or doesn't cover the full screen, so some of the paused activity can show through. A paused activity is completely...

Setting up a Device for Development

With a T-mobile G1 or Android Dev Phone 1, you can develop and debug your Android applications just as you would on the emulator. There are just a few things to do before you can start. 1. Declare your application as debuggable in your Android Manifest. In Eclipse, you can do this from the Application tab when viewing the Manifest (on the right side, set Debuggable to true). Otherwise, in the AndroidManifest.xml file, add android debuggable true to the < application> element. 2. Turn on USB...

Directing Commands to a Specific Emulator Device Instance

If multiple emulator device instances are running, you need to specify a target instance when issuing adb commands. To so so, use the -s option in the commands. The usage for the -s option is adb -s < serialNumber> < command> As shown, you specify the target instance for a command using its adb-assigned serial number. You can use the devices command to obtain the serial numbers of running emulator device instances. adb -s emulator-5556 install helloWorld.apk Note that, if you issue a...

Application Components

A central feature of Android is that one application can make use of elements of other applications (provided those applications permit it). For example, if your application needs to display a scrolling list of images and another application has developed a suitable scroller and made it available to others, you can call upon that scroller to do the work, rather than develop your own. Your application doesn't incorporate the code of the other application or link to it. Rather, it simply starts...

Application Fundamentals

Android applications are written in the Java programming language. The compiled Java code along with any data and resource files required by the application is bundled by the aapt tool into an Android package, an archive file marked by an .apk suffix. This file is the vehicle for distributing the application and installing it on mobile devices it's the file users download to their devices. All the code in a single .apk file is considered to be one application. In many ways, each Android...

Creating an Android Application using the Eclipse Plugin

Using the Android Eclipse plugin is the fastest and easiest way to start creating a new Android application. The plugin automatically generates the correct project structure for your application, and keeps the resources compiled for you automatically. It is still a good idea to know what is going on though. Take a look at Application Fundamentals to understand the basics of how an Android application works. You should also take a look at the ApiDemos application and the other sample...

User Interface Guidelines

The Android UI team has begun developing guidelines for the interaction and design of Android applications. Look here for articles that describe these visual guidelines as we release them. Widgets are a new feature introduced in Cupcake. A widget displays an application's most important or timely information at a glance, on a user's Home screen. These design guidelines describe how to design widgets that fit with others on the Home screen. They include links to graphics files and templates that...

Setting Application Version

To define the version information for your application, you set attributes in the application's manifest file. Two attributes are available, and you should always define values for both of them android versionCode An integer value that represents the version of the application code, relative to other versions. The value is an integer so that other applications can programatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you...

Audio Capture

Audio capture from the device is a bit more complicated than audio video playback, but still fairly simple 1. Create a new instance of android.media.MediaRecorder using new 2. Create a new instance of android.content.ContentValues and put in some standard properties like title, timestamp, and the all important mime_type 3. Create a file path for the data to go to you can use android.content.ContentResolver to create an entry in the Content database and get it to assign a path automatically...

Providing Mock Location Data

When testing your application on the Android emulator, there are a couple different ways to send it some mock location data you can use the DDMS tool or the geo command option in the emulator console. With the DDMS tool, you can simulate location data a few different ways Manually send individual longitude latitude coordinates to the device. Use a GPX file describing a route for playback to the device. Use a KML file describing individual placemarks for sequenced playback to the device. For...

Overview

The Android system requires that all installed applications be digitally signed with a certificate whose private key is held by the application's developer. The Android system uses the certificate as a means of identifying the author of an application and establishing trust relationships between applications. The certificate is not used to control which applications the user can install. The certificate does not need to be signed by a certificate authority it is perfectly allowable, and...

Nine PatchDrawable

A NinePatchDrawable graphic is a stretchable bitmap image, which Android will automatically resize to accomodate the contents of the View in which you have placed it as the background. An example use of a NinePatch is the backgrounds used by standard Android buttons buttons must stretch to accommodate strings of various lengths. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension .9.png, and saved into the res drawable...

Declaring a widget in the Android Manifest

First, declare the BroadcastReceiver in your application's AndroidManifest.xml file. lt action gt lt intent-filter gt The lt receiver gt element has the following attributes android name - specifies the BroadcastReceiver or AppWidgetProvider class. android label - specifies the string resource that will be shown by the widget picker as the label. android icon - specifies the drawable resource that will be shown by the widget picker as the icon. The lt intent-filter gt element tells the...

Specifying Minimum System API Version

If your application requires a specific minimum version of the Android platform, you can specify that version as an API Level identifier in the application's manifest file. Doing so ensures that your application can only be installed on devices that are running a compatible version of the Android system. To specify the minimum system version in the manifest, use this attribute android minSdkVersion An integer value corresponding to the code version of the Android platform. When preparing to...

The Basic Approach

Here is a high level overview of what you need to know to get started in creating your own View components 1. Extend an existing View class or subclass with your own class. 2. Override some of the methods from the superclass. The superclass methods to override start with 'on', for example, onDrawO, onMeasureO, and onKeyPownO. This is similar to the on events in Activity or ListActivity that you override for lifecycle and other functionality hooks. 3. Use your new extension class. Once...

Signing in Debug Mode

The Android build tools provide a debug signing mode that makes it easier for you to develop and debug your application, while still meeting the Android system requirement for signing your .apk when it is installed in the emulator or a device. When you use debug mode, the SDK tools invoke Keytool to create a debug keystore and key. The SDK tools create the debug keystore key with predetermined names passwords Keystore name - debug.keystore Keystore password - android Key alias - androiddebugkey...

Creating a new Project

If you're starting a new project, use the android create project command to generate all the necessary files and folders. To create a new Android project, open a command-line, navigate to the tools directory of your SDK and run android create project --target lt targetID gt --path path to your project --activity lt your_activity_name gt --package lt your_package_namespace gt target is the build target for your application. It corresponds to an Android platform library including any addons, such...

What Triggers ANR

In Android, application responsiveness is monitored by the Activity Manager and Window Manager system services. Android will display the ANR dialog for a particular application when it detects one of the following conditions No response to an input event e.g. key press, screen touch within 5 seconds A BroadcastReceiver hasn't finished executing within 10 seconds An ANR dialog displayed to the user. An ANR dialog displayed to the user.

Remote procedure calls

Android has a lightweight mechanism for remote procedure calls RPCs where a method is called locally, but executed remotely in another process , with any result returned back to the caller. This entails decomposing the method call and all its attendant data to a level the operating system can understand, transmitting it from the local process and address space to the remote process and address space, and reassembling and reenacting the call there. Return values have to be transmitted in the...

Pass by value Parameters using Parcelables

If you have a class that you would like to send from one process to another through an AIDL interface, you can do that. You must ensure that the code for your class is available to the other side of the IPC. Generally, that means that you're talking to a service that you started. There are five parts to making a class support the Parcelable protocol 1. Make your class implement the Parcelable interface. 2. Implement the method public void writeToParcel Parcel out that takes the current state of...

Google Maps External Library

To make it easier for you to add powerful mapping capabilities to your application, Google provides a Maps external library that includes the com.google.android.maps package. The classes of the com.google.android.maps package offer built-in downloading, rendering, and caching of Maps tiles, as well as a variety of display options and controls. The key class in the Maps package is com.google.android.maps.MapView, a subclass of ViewGroup. A MapView displays a map with data obtained from the...

Creating from resource images

A simple way to add graphics to your application is by referencing an image file from your project resources. Supported file types are PNG preferred , JPG acceptable and GIF discouraged . This technique would obviously be preferred for application icons, logos, or other graphics such as those used in a game. To use an image resource, just add your file to the res drawable directory of your project. From there, you can reference it from your code or your XML layout. Either way, it is referred...

Command Options Reference

The table below lists all options you can include on the Monkey command line. The table below lists all options you can include on the Monkey command line. Each -v on the command line will increment the verbosity level. Level 0 the default provides little information beyond startup notification, test completion, and final results. Level 1 provides more details about the test as it runs, such as individual events being sent to your activities. Level 2 provides more detailed setup information...