20-Dec-08 (Created: 20-Dec-08) | More in 'Older Android Notes'

01 Introduction

Computing continues to become personal and available. Hand held devices such as mobile phones are transforming into computing platforms. They are no longer a talking a device but capable of data, video and more importantly general purpose computing devices. In the process the battle lines of operating systems, computing platforms, programming languages, and development frameworks are being shifted reapplied to the small screen. Today's mobile phones use different operating systems such as Microsoft Windows Mobile, Linux Mobile and many proprietary extensions. Having standards and published apis in all these areas will greatly help to open the doors for a large number of applications to be available to the users at a low cost. The availability and immediacy of software through open source model has proven to be a great boon to the innovation in all areas.

One might argue that there are not enough computers in the world and they are not available to the developing countries so that everyone can participate in the global productivity and innovation. But in truth each mobile handset is a mobile computing device capable of general purpose computing and entertain and educate while also serving vital communication needs.

Google has acquired a company called Android, Inc. The key players at Android Inc, included Andy Rubin, Rich Miner, Nick Sears, and Chris White. Subsequently in late 2007 with a goal to "enrich the lives of countless people" a group of industry leaders came together around the Android platform to form the "Open Handset Aliance (OHA)". OHA web site can be found at


http://www.openhandsetalliance.com

Some of the prominent members of this alliance include

Sprint Nextel
T-Mobile
Motorola
Samsung
Sony-Ericson
Toshiba
Vodafone
Google
Intel
Texas Instruments

The stated goal of the alliance include the need to rapidly innovate and being able to respond to consumer needs. The Android platform that can serve the mobile operators, handset manufacturers, and application developers is the first key outcome of this alliance. The members have commited to release signicant intellectual property through Apache version 2 open source license. The handset manufacturers do not need to pay any licensing fees for loading Android on their handsets or devices.

The Android SDK is released first as an "early look" release in November of 2007. In September of 2008 T-Mobile has announced the availability of T-Mobile G1 based on the Android platform. A few days after that anouncement Google anounced the availability of Android SDK release candidate 1.0. In October of 2008 Google made the source of Android platform available under Apache Open Source License.

Key Principles of Android

Android platform, based on a Linix distribution, subscribes to the principle that "All Applications are created Equal", there by allowing end user applications to "play swap" with applications that come with the platform. Android platform has a number architectural features to keep this openness practical and a reality. Based on a publish-subscribe like framework of messages applications can be brokered like in an "open market" to meet the best needs of the user.

Android has fully developed featurs to exploit the cloud computing model offered by web resources and enhance that experience with the local data stores avaialable on the handset itself. Android supports a standard relational database on the handset itself as part of the base SDK. Android supports a RESTful data abstraction on all of the data storage and retrieval mechanisms.

Development features of Android

At the core of the android platform is the Linux version 2.6 kernel responsible for device drivers, resource access, and power management and other OS responsibilities. The supplied device drivers inlcude Display, Camera, Keypad, WiFi, Flash Memory, Audoi, and IPC. Although the core is linux majority, if not all, applications on the device are expected to run through the Davlik JVM. There is no documented way to port Linux apps directly to Android.

Sitting at the next level, sitting on top of the kernel are a number c/c++ libraries such as OpenGL, WebKit, FreeType, SSL, libc, SQLite, and Media Framework. The system "C" library based on BSD is tuned for embedded linux based devices. The media libraries are based on PacketVideo's OpenCORE. These libraries support recording and playback of many audio and video formats. A library called " Surface Manager" library controls access to the display system and suports 2D and 3D. The webkit library is responsible for the browser support. It is the same library that supports Chrome and also Safari. The "FreeType" library is resposible for font support. SQLite is a relational database that is available on the device itself. SQLite is also an independently open sourced effort for relational databases and not directly tied to Android. So it is possible to acquire and use tools for SQLite for Android databases as well.

Most of the application framework gets to these libraries through the Davlik JVM, the gateway to the Android platform. Every android application gets its own Davlik JVM to provide isolation. This VM is optimized to run multiple instances. The compiled java classes are further processed by a tool called "dx" to convert them to a special format for the davlik jvm to optimize memory footprint. Davlik JVM uses underlying Linux for memory management and threading needs.

On top of the Davlik JVM, Android provides a set of core java libraries to enable developers to write applications in the java programming language. The JVM is back ward compatible with JDK5 but optimized for the Android platform. So some of the features of the java experience may be different.

The main java libraries include Telephony, Resources, Locations, UI, Content providers (data), and Package managers (install, security etc).

The end user applications include Home, Contacts, Phone, Browser etc.

Android supports a custom 2D graphics library and also 3D OpenGL ES. From a media perspective Android platform supports most common audio, video, and images. Depending on the hardware it has apis to support Bluetooth, EDGE, 3G, WiFi, and GSM Telephony.

End used Application Development

All applicationd development in Android is through Java. Android provides an SDK and also an eclipse plugin called "Android Development Tool (ADT)". Both approaches support an emulator that you can use to run, debug, and test your applications.

Android uses a UI framework that is similar to other UI frameworks, albeit more modern and more asynchronous in nature. Very similar windowing concepts exist in the Android frameworks.

One key difference is the life cycle management of activity windows in Android UI. The protocols are put in place so that state can be managed as these activity windows gets hidden, restored, stopped, and closed. The UI framework along with other parts relies on a concept called "Intents". "Intents" is an amalgamation of windowing messages, actions, publish/subscribe, and inter process communications, and an application registry.

Android also has extensive support for "resources". The resources include such familiar things as strings, bitmaps and not-so-familiar things as XML based view definitions. The framework makes use of resources in a novel way to make their usage easy, intuitive and convenient.

Another new concept in Android is a "Content Provider". A "Content Provider" is an abstraction on a data source that makes it look like an emitter and consumer of RESTful services. The underlying SQLite databases makes this facility a powerful tool for application developers. You will not only get a relational database interms of SQLite but also a RESTful service abstraction.

The chapter on "Resources, Content Providers, and Intents" describes these three novel ideas and paints a picture of these three ideas promote openness in the Android platform.

On the UI front Android allows you to declare all objects as XML representations in XML files. This will remove the view and layout responsibilities from Java code. This trend is increasingly adapted in all modern UI frameworks such as Windows WPF, SilverLight, and JavaFx. Essentially a declarative approach to UI programming. This has the added benefit of being able to style these views like CSS styles HTML. These concepts are explored in chapter "???".

Android has extensive support for menus as well. All standard menus are supported including context menus. All dialogs in Android are asynchronous. These asynchronous dialogs present a special challenge to developers used to the synchronous modal dialogs in some indowing frameworks. Menus and Dialogs are extensively covered in chpater "???" and provides a number of mechanisms to deal with asynchronous dialog protocols.

Android supports tweening animation and also frame by frame animation. Android does through animation call backs, interpolators, and transformation matrices. The underlying graphics libraries support the standard transformation matrices allowing scaling, movement, and rotation. A "Camera" object provides support for depth and projection allowing a 3D like simulation on a 2D surface. The chapter on Animation covers these ideas in great depth.

Android Java Packages

Android as a platform is extensive. You can get a scope of this by looking at the list of java packages supported by Android. Each package name below is followed by the number of classes and interfaces in that package. These number kind of gives you the density of that package. For example in android.app(5I, 25C:30) stand for 5 interfaces and 25 classes totalling 30 together.

Android.App (5I, 25C: 30): This package implements the Application model for Android. Primary classes in this package include Application representing the start and stop semantics, and a number of "Activity" related classes. An Activity is a central concept in Android ,often representing a screen worth of data, controlling the life cycle of what you want to accomplish on that screen and then managing the state of that data controlled by that screen. This package also controls dialogs, alerts and notifications. An application being a collection of activities and activities being stand alone components they can be interchanged, borrowed or replaced between applications. This further strengthens the "openness" idea.

Android.Content (11I, 20C: 31): The primary classes in this package are Intent, IntentFilter, ContentProvider, Context, ContentUris, ContentResolver. Intent and IntentFilter are there for invoking actions and responding to actions. ContentProvider wraps data access in a RESTFul service. Context provides a context for such things as Activities and Applications, and Services. ContentUri are Uris that start with a "content" scheme and typically represent content providers that are registered on the device. ContentResolver is the one that orchestrates look ups from content uris and content types to content providers.

android.content.pm (1I, 20C: 21): The "pm" here stands for PackageManager. The primary classes of this package are PackageManager and a number of "Info" classes that the PackageManager will provide information on. A package manager knows about permissions, installed packages, installed providers, installed services, installed components such as activities, and installed applications.

android.content.res (1I, 8C: 9): The primary classes of this package are AssetManager and Resources. Both of these classes deal with accessing resource files and unstructured files.

android.database (2I, 17C: 19): The primary interface in this package is the Cursor interface. This package defines the abstract concept of what a database is. It has a number of abstract classes implementing the interface in preparation for a real implementation by other packages. The abstract classes allow you to merge cursors, join cursors.

android.database.sqlite(2I, 8C: 10): This is the abstract implementation of the concepts from android.database package. Primary classes in this package are SQLiteCursor, SQLiteDatabase, SQLiteQuery, SQLiteQueryBuilder, SQLiteStatement. However most of your interaction is going to be with Cursor from the abstract database package.

android.graphics (0I, 60C:60): This package is extensive which is a good indication that graphics capabilities of Android are full featured. Some of the main classes include Bitmap, Canvas, Camera, Color, Matrix, Movie, Paint, Path, Rasterizer, Shader, SweepGradient, and TypeFace.

android.graphics.drawable (1I, 20C: 21): Drawble is the central abstract class of this package. A Drawable differs from a View where by it does not receive any events or interact with user. It is used to draw such things as background images and also allow animation of these images with call backs that invalidate the drawable.

android.graphics.drawable.shapes (0I, 6C: 6): The shapes available in this package include Arc, Oval, Path, Rectangle, and Rounded Rectangle

android.hardware (6I, 4C: 10): At the moment this package hosts the Camera related classes. Camera is the main class of the package. You can use this class to work with the Camera. This Camera represents the hard ware camera while the android.graphics.Camera represents a graphical concept and not related to a physical camera at all.

android.location (1I, 6C: 7): This package has such classes as Address, GeoCoder, Location, LocationManager, LocationProvider. The address class represents the simplified xAL (extensible address language). GeoCoder allows you to get a lat long given an address and vice versa. A location represents the lat/long at a specific time and possibly altitude, speed, and bearing. A location provider enables the device to know where it is.

android.media (6I, 14C: 20): Primary classes in this package are MediaPlayer, MediaRecorder, and RingTone, AudioManager, and FaceDetector. MediaPlayer is used to play audio and video including streaming support. MediaRecorder is used to record audio and video. Ringtone class is used to play short sound snippets that could be used as ring tones and notifications. AudioManager is responsible for volume controls. FaceDetector class can be used to detect peoples faces in a bitmap.

android.net (1I, 15C: 16): Basic socket level network apis. Primary classes include Uri, ConnectivityManager, LocalSocket, LocalServerSocket.

android.net.wifi (0I, 11C: 11): This package is responsible for managing wifi connectivity. Primary classes include WifiManager and WifiConfiguration. WifiManager is responsible for such things as listing the configured networks and the currently active wifi network.

android.opengl (0I, 4C: 4): This package provides the opengl operations.

android.os (6I, 40C: 46): This package represents the OS services accessible through the java programming language. Some important classes include BatteryManager, Binder, FileObserver, Handler, Looper, PowerManager. Binder is a class that allows inter process communications. FileObserver is to keep tabs on changes to files. Handler classes are used to run tasks on the message thread. Looper is used to run a message thread.

android.preference (5I, 12C: 17): This package allows applications to manage their preferences in a uniform way. The primary classes are PreferenceActivity, PreferenceScreen, and various Preference derived classes such as CheckBoxPreference, and SharedPreferences.

android.provider (20I, 50C: 70): The excessive number of interfaces and classes in this package is a mis-indicator of code density of Android. This package is basically a set of pre built content providers adhering to the android.content.ContentProvider interface. The content providers include Contacts, MediaStore, Browser, and Settings. The set of interfaces and classes sort of store the meta data for the underlying data structures.

android.sax (5I, 2C: 6): An efficent set of SAX parsing utility classes. Primary classes include Element, RootElement, and a bunch of element listener interfaces.

android.telephony: (6C): The important classes are CellLocation, PhoneNumberUtils, TelephonyManager. A TelephonyManager lets you find out about cell location, phone number, network operator name, net work type, phone type, and sim serial number.

android.telephony.gsm: (4C): This package allows you to gather cell location based on cell towers and also hosts classes resonsible for SMS messaging. This is because GSM is the technology that allowed originally the SMS data messaging standard. GSM is a standard for mobile phones allowing roaming among carriers. It is a digial system. It is also called 2G for second generation. GSM also allowed a universal emergency number "112" anywhere in the world. In 97 it added General Packet Radio Service (GPRS). In 99 it allowed higher data transmission speeds using Enhanced Data Rates for GSM evolution (EDGE). GSM is also a standard for cellular networks. GSM operates in 4 frequency ranges 900Mhz, 1800Mhz, 850Mhz, 1900 Mhz, 400 Mhz, 450Mhz. GSM also specifies sampling rate, transmission speed, and cell types. The maximum distance GSM allows is 35Km. The concept of SIM is essentially a GSM concept. It is possible to lock a SIM through SIM locking. It is not allowed to lock SIMs in some countries.

The GSM based phones are sometimes characterized as EDGE and 2G phones accomodating data speeds upto 384kbps. The phones in the market recently started supporting the 3G standard which enhances GSM but is called UMTS: Universal Mobile Telecommunication System. This is considered next generation of GSM. UMTS uses "code division multiple access" (CDMA) as opposed to "Time Division Multiple Access" (TDMA) to accomodate higher speeds. It can support 14Mb/sec data transfer rate. However current 3G handsets may be supporting only 400Mb/sec in practice. Advanced GSM using packet switching can support 56kbps. with EDGE you can reach 180kbps. HSDPA (High Speed Downlink Packet Access) enables download speeds of 7.2mbs. Next evolution of UMTS (4G) is expected to support 100mbps down and 50mbps up using orthogonal frequency-division multiplexing. The 3G frequencies are 850/900/1700/2100. There are no universal handsets that support all these frequencies. With 2G and 3G combined there are over 11 frequency bands that are in use.

Another standard is also taking root for wireless wide area networks called EVDO - Evolution Data Only. It is a wireless broadband data access standard for DSL like data speeds with out any need for hot spots. data speeds are 500kbps to 1000kpbs. Unlike GSM it is not a mobile standard but a general purpose data standard like wi-fi. On an edge network (GSM based) it may take 90 seconds to download 1 Mb of file. On an EVDO network it takes about 10 secs for the 1MB file. At the moment sprint and verizon supports EVDO cards for laptops.

To summarize as you read through mobile telephone technologies you may want to consider the following speed comparisions between different technologies: GSM normally supports 14.4kbps. The advanced EDGE (GSM family of standards) supports 384kbps. EVDO could support 500mbps to 2mbps.

android.text (10I, 25C: 35): Contains text processing classes.

android.text.method (3I, 15C: 18): provides classes for entering text input for a variety of controls. Includes methods for key presses.

android.text.style (8I, 40C: 48): Provides a number of sytling mechanisms for a span of text.

android.utils: (2I, 20C: 22): Main classes in this package include Log, DebugUtils, TimeUtils, and Xml utils.

android.view: (30I, 30C: 60): This package is the core UI package. The main classes in this package include Menu, View, ViewGroup, and a series of listeners and callbacks.

android.view.animation (2I, 20C: 22) : This package provides support for tweening animation. The main classes inlude Animation, a series of interpolators for animation, AlphaAnimation, ScaleAnimation, and TranslationAnimation.

android.webkit: (5I, 25C: 30): This package has classes representing the web browser. The primary classes include WebView, CacheManager, CookieManager

android.widget: (35I, 70C: 105): This package contains all of the UI controls usually derived from the View. Primary widgets include Button, Checkbox, Chronometer, AnalogClock, DatePicker, DigitalClock, EditText, ListView, FrameLayout, GridView, ImageButton, MediaController, ProgressBar, RadioButton, RadioGroup, RatingButton, Scorller, ScrollView, Spinner, TabWidget, TextView, TimePicker, VideoView, and ZoomButton.

com.google.android.maps: (2I, 10C: 12): Main classes of this package include Google MapView, MapController, MapActivity. Essentially classes required to work with google maps.

These are some of the crtical android specific packages. From this list you can see the depth of the android core platform. In all there are over 36 packages and over 700 classes. Even if each class spreads for 4 single spaced pages you can imagine a book that spans to over 3000 pages of material.

in addition android provides a number packages in the java namespce. These include awt.font, io, lang, lang.annotation, lang.ref, lang.reflect, math, net, nio, nio.channels, nio.channels.spi, nio.charset, security, security.acl, security.cert, security.interfaces, security.spec, sql, text, util, util.concurrent, util.concurrent.atomic, util.concurrent.locks, util.jar, util.logging, util.prefs, util.regex, and util.zip.

From the javax namespace it comes with crypto,crypto.spec, microedition.khronos.egl, microedition.khronos.opengles, net, net.ssl, security.auth, security.auth.callback, security.auth.login, security.auth.x500, security.cert, sql, xml, xmlparsers.

In addition it carries a lot of packages from org.apache.http.*. It also carries org.json, org.w3c.dom, org.xml.sax, org.xml.sax.ext, org.xml.sax.helpers, org.xmlpull.v1, org.xmlpull.v1.sax2.

Together these numerous packages provide a rich computing platform to write applications with.

Android Source Code

Android as a platform is very attractive to java programmers because it exposes an entire operating system through a java api. However during these early releases documentation is a bit "wanting" at places. When you run into something like that it is worthwhile exploring android source code to fill the gaps.

The details of Android source distribution is published at http://source.android.com. The code was open sourced around October 2008. This announcement is available at http://source.android.com/posts/opensource. One of the goals of the open source announcement is to make Android a free and fully customizable mobile platform. The announcement strongly suggests that Android platform is a fully capable mobile computing platform with no gaps. The open source model allows contributions from non core team members from the public communities.

As indicated Android is just not one project but a massive effort with a number of projects. You can see the scope and the number of these projects at http://source.android.com/projects

The source code of Android and all its projects is managed by the "git" source code control system. GIT is an open sourced source control system designed to handle large and small projects with speed and convenience. Some of the other projects managed by "git" include linux kernel, Ruby On Rails, The list of android projects in the "git" can be found at http://android.git.kernel.org/

Any of these projects can be downloaded using the tools provided by "git" and described at the "git" website http://git.or.cz/. Some of the primary projects include dalvik, frameworks/base (the android.jar), kernel, and number of external libraries such as Apache http. The core android applications are also hosted here. Some of the core applications include

AlarmClock, Browser, Calculator, Calendar, Camera, Contacts, Email, GoogleSearch, HTML Viewer, IM, Launcher, Mms, Music, PackageInstaller, Phone Settings, SoundRecorder, Stk, Sync, Updater, and VoiceDialer.

The projects also include the "Provider" projects. These projects are CalendarProvider, ContactsProvider, DownloadProvider, DrmProvider, GoogleContactsProvider, GoogleSubscribedFeedsProvider, ImProvider, MediaProvider, SettingsProvider, SubscribedFeedsProvider, and TelephonyProvider.

As a programmer the source code that you often want to visit is the source code that makes up the "android.jar". Instead if your interest is to download the entire platform and build it yourself refer to the documentation available at the following android website http://source.android.com/download

Coming back to the android.jar you can download the source for this jar file by typing in the following url http://git.source.android.com/?p=platform/frameworks/base.git;a=snapshot;h=HEAD;sf=tgz

This is one of the general purpose "git" urls you can use to download "git" projects. On windows you can unzip this file using pkzip.

How can I see source files online?

Although you can download and unzip the sources, it might just be more convenient to just look at these files online if you are not in need of debugging into the source code. "git" also allows you to do this. For example you can browse through android.jar source files by visiting

http://android.git.kernel.org/?p=platform/frameworks/base.git;a=summary

Ofcourse you have to do somework after you visit this page. Once you are there, you will see a drop down. Pick "grep" from the drop down. Type in the text that you would like to see in a file that you want to search for that string just like grep. You will see a list of files in response. Click on one of the file names to open the file in your browser. Very convenient.

At times the file you are looking for may not be in the fraeworks/base directory or project. Then you need to find the list of projects and see each one step by step. The url for this list is:

http://android.git.kernel.org/

There is not a way that I know of where you can grep across all projects. So you will need to know which project belongs to which facility in Android. For example the "graphics" related libraries are availabe in the project of "skia" available at

http://android.git.kernel.org/?p=platform/external/skia.git;a=summary

Here is an example looking at teh SkMatrix.cpp file that has the source code for transformational matrix that is useful in animations:

http://android.git.kernel.org/?p=platform/external/skia.git;a=blob;f=libcorecg/SkMatrix.cpp

In a similar tone here is the source code for the corresponding cpp header file for SkMatrix

http://android.git.kernel.org/?p=platform/external/skia.git;a=blob;f=include/corecg/SkMatrix.h

How can I debug using the source for android.jar?

Eclipse has a facility that allows you to attach source to a library jar such as android.jar. The general approach is as follows.

Look for the jar that you have source for in the "Referenced Libraries" underneath your project in the project explorer. Expand "Referenced Libraries" by opening the plus sign.

Click on the jar file and right click for properties. You will see an option called "Java Source Attachment". Specify the path or the jar file of the source here.

These steps may vary depending on the eclipse release. However bottomline is that you can attach source to an existing jar.

Occasionally though the source options for a jar are turned off as the jar file is indicated as an immutable system library. In such cases you may want to drop or remove the jar file and that library and explicitly add it as a user library as if you are attaching that jar yourself and then proceed to attach source code to it.

This indeed is the case for android.jar. For the projects you have created as "android" projects through the android development Tool (ADT) plugin for eclipse, android.jar is locked down from modifications. You will have to "remove" that library and reattach it as just another library. Then you can attach the source folder that you have downloaded using one of the steps above. Then you will be able to step into the android java source code. Some of these java calls may end up in calling native code that is in "c" or "c++" in which case you can use the browse online option to look at the source code manually through a web browser.

Show me the code: A quick look at some android code

Some times technology is better perceived through its code. In that spirit let me conclude this chapter by showing you some routine sample code.

In android at a high level screens are designed by declaring their views in xml files.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView android:id="@+id/textViewId"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    
<TextView android:id="@id/myviewId"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Just Plain Text"
    />
</LinearLayout>

Here is how string resources are defined


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World</string>
    <string name="app_name">Main Menus</string>
    <item type="id" name="myviewId"/>
</resources>

Here is how frame animations are declared in a user chosen file say "res/drawable/myanimation.xml"


<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
	android:oneshot="false">
    <item android:drawable="@drawable/numbers11" android:duration="50" />
    <item android:drawable="@drawable/numbers12" android:duration="50" />
    <item android:drawable="@drawable/numbers13" android:duration="50" />
    <item android:drawable="@drawable/numbers14" android:duration="50" />
    <item android:drawable="@drawable/numbers15" android:duration="50" />
    <item android:drawable="@drawable/numbers16" android:duration="50" />
    <item android:drawable="@drawable/numbers17" android:duration="50" />
    <item android:drawable="@drawable/numbers18" android:duration="50" />
    <item android:drawable="@drawable/numbers19" android:duration="50" />
 </animation-list>

Where each item represents an image under the "drawable" resource sub directory.

Here is how the resources are given ids that could be used in java source


public final class R {

    public static final class attr {
    }
    public static final class drawable {
        public static final int myanimation=0x7f020001;
        public static final int numbers1=0x7f020005;
		.....
        public static final int numbers18=0x7f02000d;
        public static final int numbers19=0x7f02000e;
    }
	
    public static final class id {
        public static final int animationImage=0x7f080005;
        public static final int container=0x7f080001;
        public static final int myviewId=0x7f080000;
        public static final int picture=0x7f080002;
        public static final int startFAButtonId=0x7f080004;
        public static final int textViewId=0x7f080006;
        public static final int textViewId1=0x7f080003;
    }
    public static final class layout {
        public static final int animations_main_screen=0x7f030000;
        public static final int frame_animations_layout=0x7f030001;
        public static final int main=0x7f030002;
    }
    public static final class string {
        public static final int app_name=0x7f070001;
        public static final int hello=0x7f070000;
    }
}

Here is how you declare menus


<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This group uses the default category. -->
    <group android:id="@+id/menuGroup_Main">
        <item android:id="@+id/menu_clear"
            android:orderInCategory="10"
            android:title="clear" />
        <item android:id="@+id/menu_dial"
            android:orderInCategory="7"
            android:title="dial" />
        <item android:id="@+id/menu_test"
            android:orderInCategory="4"
            android:title="@+string/test" />
        <item android:id="@+id/menu_show_browser"
            android:orderInCategory="5"
            android:title="show browser" />
    </group>
</menu>

Here is how you load a menu and attach to an application


public boolean onCreateOptionsMenu(Menu menu) 
{
	//call the parent to attach any system level menus
	super.onCreateOptionsMenu(menu);

	MenuInflater mi = this.getMenuInflater();
	mi.inflate(R.menu.main_menu,menu);

	return true;
}

here is how you start off writing an application


public class HelloWorld extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		
		//attach a view 
        setContentView(R.layout.main);
}

Here is another way of adding menu items manually


private void addRegularMenuItems(Menu menu)
{
	//Secondary items are shown just like everything else
	int base=Menu.FIRST; // value is 1

	MenuItem item1 = menu.add(base,base,base,"append");
	menu.add(base,base+1,base+1,"item 2");
	menu.add(base,base+2,base+2,"clear");
	
	//This will show the icon
	item1.setIcon(R.drawable.balloons);
}

here is how you invoke a web browser


public static void invokeWebBrowser(Activity activity)
{
	Intent intent = new Intent(Intent.ACTION_VIEW);
	intent.setData(Uri.parse("http://www.google.com"));
	activity.startActivity(intent);
}

here is how you make a call


public static void call(Activity activity)
{
	Intent intent = new Intent(Intent.ACTION_CALL);
	intent.setData(Uri.parse("tel:904-905-5646"));
	activity.startActivity(intent);
}

Here is how you invoke a google Map


public static void showMapAtLatLong(Activity activity) 
{
	Intent intent = new Intent(Intent.ACTION_VIEW);
	//geo:lat,long?z=zoomlevel&q=question-string
	intent.setData(Uri.parse("geo:0,0?z=4&q=business+near+city"));
	activity.startActivity(intent);
}

Here is how your application is registered through its manifest file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.ai.android.HelloWorld"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".HelloWorld"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".animation.Demo3d"
                  android:label="@string/app_name">
        </activity>
        <activity android:name=".frameanimation.FrameAnimationActivity"
                  android:label="Frame Animation Test">
        </activity>
    </application>
</manifest>

Layouts are an important part of any UI framework. Android supports 5 of them as of this writing, Linear, Tabular, Relative, Absolute, and Frame. You have already seen the LinearLayout in examples above. Here are some examples of others to get an idea what these look like.

Let us continue with a table layout


<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent">

	<TableRow>
		<TextView android:layout_width="wrap_content" 
		android:layout_height="wrap_content" android:text="First Name:"/>
	
		<EditText android:layout_width="wrap_content" 
		android:layout_height="wrap_content" android:text="Barak"/>
	</TableRow>		
	<TableRow>
		<TextView android:layout_width="wrap_content" 
		android:layout_height="wrap_content" android:text="Last Name:"/>
	
		<EditText android:layout_width="wrap_content" 
		android:layout_height="wrap_content" android:text="Obama"/>
	</TableRow>	
</TableLayout>

Here is relative layout


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content">
<TextView android:id="@+id/userNameLbl" 
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="Username: "
		android:layout_alignParentTop="true" />
		
<EditText android:id="@+id/userNameText" ....
     android:layout_below="@id/userNameLbl" />
		
<TextView android:id="@+id/disclaimerLbl" ... 
		android:layout_alignParentBottom="true"...
		/>
</RelativeLayout>

Here is absolute layout with its properties


<AbsoluteLayout ..>
	<TextView ...
	android:text="Username:"
	android:layout_x="50px"
	android:layout_y="50px" />
	
	<EditText ...
	android:layout_x="160px"
	android:layout_y="50px" />
</AbsoluteLayout>

Android has all the expected http connectivity including POST. Here is an example of how we do a multi-part post


InputStream is = this.getAssets().open("data.xml");
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://192.178.10.131/WS2/Upload.aspx");

byte[] data = IOUtils.toByteArray(is);

InputStreamBody isb = new InputStreamBody(
					new ByteArrayInputStream(data),"uploadedFile");
StringBody sb1 = new StringBody("someTextGoesHere");
StringBody sb2 = new StringBody("someTextGoesHere too");

MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("uploadedFile", isb);
multipartContent.addPart("one", sb1);
multipartContent.addPart("two", sb2); 

postRequest.setEntity(multipartContent);
HttpResponse res =httpClient.execute(postRequest); 
res.getEntity().getContent().close();

Android supports interprocess communications among services using AIDL. Here is an example of AIDL


package com.syh;
interface IStockQuoteService 
{ 
        double getQuote(String ticker); 
} 

Android generates the interfaces and stubs based on this definition. You will implement the service as follows


public class StockQuoteService extends Service 
{
	public class StockQuoteServiceImpl extends IStockQuoteService.Stub
	{
		@Override
		public double getQuote(String ticker) throws RemoteException 
		{
			return 20.0;
		}
	}
	...some stock methods	
	@Override
	public IBinder onBind(Intent intent) 
	{
		return new StockQuoteServiceImpl();
	}
}

Here is how you register that service in android manifest file


<service android:name="StockQuoteService">
	<intent-filter>
		<action android:name="com.syh.IStockQuoteService" />
	</intent-filter>
</service>

Here is how you request to be connected to a service


ServiceConnection serConn = new ServiceConnection();
....
bindService(new Intent(IStockQuoteService.class
		 .getName()),
			serConn, Context.BIND_AUTO_CREATE);

You will get a call back when you are connected


@Override
public void onServiceConnected(ComponentName name, IBinder service) 
{
	stockService = IStockQuoteService.Stub.asInterface(service);
	double val;
	try {
		val = stockService.getQuote("syh");
		Toast.makeText(MainActivity.this, 
		   "Value from service is "+val+"", Toast.LENGTH_SHORT).show();
	} catch (RemoteException ee) {
		Log.e("MainActivity", ee.getMessage(), ee);
	}
}

As you go through the rest of the book you will learn all of these aspects of Android and lot more with a focus in-depth understanding and also examples that are clearly annotated to lead you through the internals of Android.