整体概况
Beginning Android 2 Mark Murphy著
Android设备总的来说,还是手机。虽然正在讨论将Android的技术用在其他领域(车载电脑),但是你能想到绝大部分设备还是所使用的Android手机。对于开发人员,这是优点和缺点并存的。从另一方面来说,大约是在2009,Android类型的手机还是比较有吸引力的。通过移动设备提供互联网服务的历史可以追溯到90年代中期以及手持设备标记语言(HDML)。但是直到近些年,移动设备才真正具有互联网接入能力。现在,由于传统的手机功能,如文字短信,和一些产品,比如苹果的手机,手机才作为一个互联网接入手段非常快地流行起来。因此,用Android应用程序工作将给你一个有趣的技术体验,在快捷的移动市场领域(具有互联网接入能力的手机),始终是一件好事。同时,当你要编程实现一些东西时,该死的麻烦也随之而来。任何有过类似于PDA编程经验的人都有这种痛苦,这个痛苦的根源就是小:
屏幕尺寸太小(你不可以在口袋里装一个24寸的LCD吧,所以……)
键盘很小(如果有的话)
点击设备(如果有的话)让人很无语(就像那些把触摸笔弄丢了的人所告诉你的一样)或者是不正确的(大指头在多点触摸(“multi-touch”)的LCD上总是按不对)
CPU的速度和内存的大小和你使用的桌面设备不可同日而语。
如果你愿意你可以选任何编程语言和设备框架,只要它们是厂商支持的,并且已经写入了移动设备中的硅元素中。等等……更重要的是,现在运行在手机上的程序必须面对一个事实:真的要在手机上运行。当人们的手机工作不正常时,人们会变得非常暴躁,这就是VerizonWireless的广告“Canyouhearmenow?”变得这么流行的原因。同样的,当你的程序以下面的方式“破坏”人们的手机时,他们也会变得很气愤:
你一直占着CPU,电话打不进来与手机的操作系统兼容性不怎么样,比如当有电话打来时,或者当用序退到后台,但是你的程序却不能正常地退到后台直接引起手机操作系统的崩溃,比如你的程序像一个筛子一样引起内存泄露所以编写一个手机应用程序和你编写一个桌面应用程序,网站,或者类似于后台服务的经验是完全不同的,你必须处理不同的查看设备(different-lookingtools),不同的框架行为(different-behavingframeworks),和“不同而不是适应”("differentthanyou'reusedto")的对你编程的各种限制。
Android所尝试的是要满足半路出家的你:
你可以用一个非常常用的编程语言(Java)和被广泛应用的库(比如一些Apached的常用API)以及支持你常用的一些编程工具(Eclipse)你可以得到一个非常坚挺和独立的框架,使得你的程序能够成为手机上的一个“好市民”,并且不会干扰手机上的其他程序或者操作系统。或许正如你所希望的那样,这本书的大部分是给你介绍怎么编程和处理各种限制,并且利用它(Android-译者注)的各种能力。
Android是由什么组成的
当你在写一个桌面程序时,你是“自己领域的上帝”。当你需要时你可以加载自己的主窗口和任何子窗口——比如对话框。从你的角度来说,你处在一个操作系统支持各项特性的世界,并且很大程度上的忽略其他可能与此同时运行的应用程序。当你和其他操作系统进行交互时,一般都是通过API,比如利用JDBC(或者凌驾于它之上的框架)和MySQL或者其他的数据库进行通信。
Android有着相似的概念,但是打包的形式不一样,Android的设计是为了让手机系统更加的坚挺。
Activity
组成用户接口这个大厦的“砖”就是activity。你可以把activity想象成Android中类似于的桌面程序中的窗口或者对话框。虽然activity可能不具有用户界面,最有可能你的“没有脸的”(headless)的代码(这里指你的程序对用户不可见——译者)将被以服务或者contentprovider的形式打包,正如我们下面要讲到的一样。户要求你的程序退到后台,但是你的程序却不能正常地退到后台直接引起手机操作系统的崩溃,比如你的程序像一个筛子一样引起内存泄露,所以编写一个手机应用程序和你编写一个桌面应用程序,网站,或者类似于后台服务的经验是完全不同的,你必须处理不同的查看设备(different-lookingtools),不同的框架行为(different-behavingframeworks),和“不同而不是适应”("differentthanyou'reusedto")的对你编程的各种限制。
Android所尝试的是要满足半路出家的你:
你可以用一个非常常用的编程语言(Java)和被广泛应用的库(比如一些Apached的常用API)以及支持你常用的一些编程工具(Eclipse)你可以得到一个非常坚挺和独立的框架,使得你的程序能够成为手机上的一个“好市民”,并且不会干扰手机上的其他程序或者操作系统。
或许正如你所希望的那样,这本书的大部分是给你介绍怎么编程和处理各种限制,并且利用它(Android-译者注)的各种能力。
Android是由什么组成的
当你在写一个桌面程序时,你是“自己领域的上帝”。当你需要时你可以加载自己的主窗口和任何子窗口——比如对话框。从你的角度来说,你处在一个操作系统支持各项特性的世界,并且很大程度上的忽略其他可能与此同时运行的应用程序。当你和其他操作系统进行交互时,一般都是通过API,比如利用JDBC(或者凌驾于它之上的框架)和MySQL或者其他的数据库进行通信。
Android有着相似的概念,但是打包的形式不一样,Android的设计是为了让手机系统更加的坚挺。
Activity
组成用户接口这个大厦的“砖”就是activity。你可以把activity想象成Android中类似于的桌面程序中的窗口或者对话框。
虽然activity可能不具有用户界面,最有可能你的“没有脸的”(headless)的代码(这里指你的程序对用户不可见——译者)将被以服务或者contentprovider的形式打包,正如我们下面要讲到的一样。
ContentProvider
Contentprovider提供了一个所有程序都能访问的存储在设备中的数据的抽象。同样Android的开发模型鼓励你将自己的数据设计成对其他程序也是可用的,就象访问你自己的数据一样的——当你维护一个完全可用的自己的数据访问时,或者组建一个contentprovider时它就会让你做这样的事情,
Intent是系统的消息,运行在系统设备内部,用以通知程序各种各样的事件:从硬件状态的改变(比如SD卡的插入)到数据的到达(比如来了一条短信),再到应用程序的事件(比如你的程序应用程序从主菜单中启动)。你不只可以对intent做出反应,还可以创建你自己的intent去启动其他的activity,或者用以通知你自己一个特定状态的出现(比如当用户到达一个特定位置100米的范围之内时发送一个特定的Intent)。
Service
Activity,contentprovider,和intentreceiver的生命周期都是比较短的,并且随时可以被关闭。service在另一方面被设计成如果需要,可以独立于任何的activity而一直保持运行。你可以用一个service来检查RSS的更新,或者播放后台音乐,即使那个主控的activity已经不再运行了。
一切任你支配
Android是伴随着很多可以帮助你编程的特性出现的。
存储
你可以用自己的应用程序对数据文件(是指那些一般不会变的比如图标或者帮助文件)进行打包。你也可以自己在设备上开辟一块小空间,用于存保存用户输入或者你的程序将要用到的数据或者文件。如果用户提供了一个巨型的存储设备比如SD卡,你可以在需要时对其进行读写。
网络
Android通常情况下是通过一个交互媒介而对互联网络可读的。你可以利用互联网进行各种层次的互联网数据访问。如果你希望的话,可以用原始的java套接字为你的程序去创建一个WebKit为基础的浏览器。
多媒体
Android设备具有对音频和视频的回放能力。虽然设备与设备的实现细节不同,但是你可以查询下设备的能力,然后去用你认为合适的多媒体功能。不论是去播放音乐,用摄像头拍照,还是利用麦克风去做一个语音记录。
GPS
Android设备会经常访问locationprovider比如GPS,它可以告诉你的应用程序这个设备出现在地球表面的哪个地方。接下来,你就可以显示一幅地图或者利用得到的这个位置数据,比如你可以在这个设备被偷了时去跟踪这个设备的移动情况。
手机服务
当然,Android设备也是一个典型的手机,允许你的软件去初始化一个(语音——译者)通话、发送一个短消息,或者其他现在所有的电话技术。
项目和目标
基本概念
在开发Android应用程序之前,必须创建一个相应的Android项目。如果你使用Eclipse开发的话,那就是创建一个Eclipse项目。这个项目将会保存所有源代码、资源(例如国际化字符串)、第三方JAR及相关内容。Android构建工具(集成在Eclipse中的或独立的构建工具)会将项目的内容转换成APK(Android Package,Android包)文件,这就是Android应用程序。这些工具还可以帮你把APK文件部署到Android模拟器,或者部署到真实的Android设备中,以便测试。项目中的最关键的一个元素是描述文件(manifest),即AndroidManifest.xml。这个文件中包含着应用程序的“目录”,列出了主要的应用程序组件、权限,等等。Android在运行时会通过这个描述文件将应用程序与操作系统关联起来。此外,Android Market(或其他独立的“应用程序商店”)也会用到这些描述文件,以便使Android 2.0的应用程序不会被安装到运行Android 1.5的设备上。
要使用模拟器来测试应用程序,必须先创建一个AVD(Android Virtual Device,Android虚拟设备)。多数情况下,都需要创建很多AVD,每个AVD分别模拟一种基于特硬件的Android设备。此外,还可以为不同屏幕尺寸、不同Android版本创建不同的AVD。
在创建项目和AVD时,需要为Android指定要使用的API级别。API级别是一个整数值,不同的整数值映射到不同的Android版本(例如,API 3对应Android 1.5)。创建项目时,可以告诉Android你的应用程序支持的最小和最大API级别。而在创建AVD时,则是告诉Android新建的这个AVD要模拟哪个级别的API。这样,就可以看到自己的应用程序在支持不同Android版本的不同(模拟)设备上运行的效果了。
创建项目 要想在命令行中创建项目(以便使用ant等构建工具),需要运行android create project命令。这个命令带有一些参数,用于指定应用程序代码所属的Java包、应用程序针对的API级别,等等。成功运行命令后,会得到一个文件夹,其中包含构建基本的Android应用程序所需的全部文件。 下面是一个android create project命令的示例: android create project --target 2 --path ./FirstApp --activity FirstApp –package apt.tutorial 如果你想使用Eclipse开发Android应用程序,而不是使用android create project方式,那么就需要使用Eclipse的新项目向导来创建一个新Android应用程序。 注意:本书的源代码是按照使用命令行构建工具构建应用程序而创建的。如果你要使用Eclipse 可以创建空Eclipse项目,再将代码导入到项目中 。
项目结构 每个Android项目都包含一套特定的目录树结构(非常类似Java项目),而Android构建系统就是基于该目录树结构组织的。不过,Android的这套目录结构还是有点与众不同。下面我们就来简单介绍一下Android项目的目录结构,以便读者有个大概的印象,特别是让你能够轻松地看明白本书给出的示例代码。
根目录 在创建了新Android项目后(例如通过android create project命令),你会在项目的根目录下发现一些文件和子目录,以下是对它们的简要说明。 AndroidManifest.xml:是一个XML文件,用于描述将被构建的应用程序,以及应用程序中包含哪些组件(Activity、Service,等等)。
build.xml:是一个Ant脚本,用于编译应用程序和在设备上安装应用程序。 default.properties和local.properties:是属性文件,由Ant构建脚本使用。
assets/:文件夹,用于保存需要打包到应用程序中的静态文件,以便部署到设备中。
bin/:文件夹,用于保存编译后的应用程序。
gen/:文件夹,Android构建工具放置它们生成的源代码的地方。
libs/:文件夹,用于保存应用程序用到的第三方JAR。
src/:文件夹,用于保存应用程序的Java源代码。
res/:文件夹,用于保存应用程序的资源(如图标、GUI布局等),将被打包到编译后 Java中。
tests/:文件夹,用于保存完全独立的Android项目,以便测试你所创建的项目。
主Activity
在创建Android项目时(例如通过android create project命令),我们为应用程序的主活动指定了一个完整的类名(例如:com.commonsware.android.SomeDemo)。然后,你就会在项目的src/目录下看到映射过来的命名空间目录树结构,以及一个表示主活动的Activity的待实现子类(例如,src/com/commonsware/android/SomeDemo.java)。你可以修改这个文件,或者再向这个目录中添加实现应用程序所需要的其他文件。
首次编译项目时(例如通过ant命令),Android在构建项目时会在主活动命名空间目录的外部创建R.java。这个文件中包含很多常量,与你放在res/文件夹中的各种资源一一对应。在阅读本书的过程中,你会发现很多示例中都会引用R.java(例如,R.layout.main就是引用布局文件的标识符)。
注意:你不能动手修改R.java,Android工具会为你自动创建和更新这个文件。
资源
如前所述,res/目录中保存着资源,即将会打包到应用程序中的静态文件(可能是原始格式,也可能是经过预处理的格式)。下面介绍res/目录下的一些子目录,有些是自动创建的,有些则是需要你自己创建的。
res/drawable/:存放图像(PNG、JPEG,等等)
res/layout/:存放基于XML的UI布局描述 res/menu/:存放基于XML的菜单描述
res/raw/:存放通用的文件(如,包含账号信息的CSV文件) res/values/:存放字符串、尺寸值
res/xml/:存放通用的XML文件
所有这些文件夹(以及其他资源)都会在本书中提到。
编译结果
在编译项目时(通过ant命令或IDE),编译结果将被放到项目根目录下的bin/文件夹中,这个文件夹中的情况如下。
bin/classes/:存放编译后的Java类文件
bin/classes.dex:存放基于编译后的Java类创建的可执行文件
bin/yourapp.ap_:存放应用程序的资源,打包为ZIP文件(这里的yourapp是你应用程
序的名称)
bin/ yourapp-debug.apk或bin/ yourapp-unsigned.apk:实际的Android应用程序(这里的
yourapp是你应用程序的名称) 其中,.apk文件是一个ZIP压缩文件,包含.dex文件、资源的编译版(resources.arsc)、其他未编译的资源(如放在res/raw/中的资源)以及AndroidManifest.xml文件。.apk文件也是经过数字签名的文件,文件名中的-debug表示已经使用模拟器认可的调试密钥签名,-unsighed表示待发布的应用程序(ant release),但还需要使用jarsigner及正式密钥进行签名。
AndroidManifest.xml文件
描述文件是所有Android应用程序的基础,本节就来介绍这个位于项目根目录下的AndroidManifest.xml文件。除了在这个文件中声明应用程序中都包含哪些组件(如Activity、Service,等等),还要指出它们怎么附加到整个Android系统中。例如,可以指定某个(某些)
Activity应该出现在设备的主菜单中(主菜单也称为“启动菜单”)。
在创建应用程序的时候,将会自动生成一个基本的AndroidManifest.xml文件。对简单的应用程序来说,这个文件中可能只包含一个Activity。此时,使用自动生成的描述文件可能也没有问题,但有时候也需要对它进行一些小小的改动。另一方面, Android API演示套件所使用的描述文件则非常庞大,有1 000多行。至于你自己开发的应用程序,其大小很可能会介于上述二者之间。
关于描述文件中那些最重要的部分,本书都会在讨论相关的Android特性时进行较为详细地介绍。例如,第29章会详细介绍<service>元素,而那一章的主题是创建服务。就目前而言,只要理解描述文件的作用及其一般性结构就足够了。
一开始是根元素
所有描述文件的根元素都是——当然,没有什么好奇怪的——<manifest>元素:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android.search"> ...
</manifest>
注意命名空间声明。有点奇怪吧?在这个生成的描述文件中,只有特性(attribute)带有命名空间前缀,元素上反而没有(例如,是manifest而非android:manifest)。在Android应用程序中,这种做法是有效的,除非Android以后会变,否则建议你还是遵守这一约定。 在<manifest>元素中,需要指定的最长的信息就是package特性(奇怪的是,也不需要在这个特性前面添加命名空间前缀)。在这里,可以提供作为应用程序“基准”的Java包的名字。此后,只要描述文件中其他地方需要类名,都可以用前置的点号来作为这个包的简写。例如,你需要在前面的描述文件中引用com.commonsware.android.search.Snicklefritz,那么可以只
使用.Snicklefritz,因为已经将com.commonsware.android.search定义为这个应用程序的包了。
The Big Picture
Android devices, by and large, will be mobile phones. While the Android technology is
being discussed for use in other areas (e.g., car dashboard “PCs”), for now, the focus is
on phone applications. For developers, this has benefits and drawbacks.
Challenges of Smartphone Programming
On the plus side, Android-style smartphones are sexy. Offering Internet services over
mobile devices dates back to the mid-1990s and the Handheld Device Markup
Language (HDML). However, only in recent years have phones capable of Internet
access taken off. Now, thanks to trends like text messaging and products like Apple's
iPhone, phones that can serve as Internet-access devices are rapidly gaining popularity.
So, working on Android applications gives you experience with an interesting technology
(Android) in a fast-moving market segment (Internet-enabled phones), which is always a good thing.
The problem comes when you actually have to program the darn things.
Anyone with experience in programming for PDAs or phones has felt the pain of phones
simply being small in all sorts of dimensions, such as the following:
Screens are small (you won’t get comments like, “Is that a 24-inch LCD in your pocket, or...?”).
Keyboards, if they exist, are small.
Pointing devices, if they exist, are annoying (as anyone who has lost a stylus will tell you) or inexact (large fingers and “multitouch” LCDs are not a good mix).
CPU speed and memory are limited compared with what are available on desktops and servers.
You can have any programming language and development framework you want, as long as it was what the device manufacturer chose and burned into the phone’s silicon.
Moreover, applications running on a phone must deal with the fact that they are on a phone.
People with mobile phones tend to get very irritated when those phones don’t work, which is why the “Can you hear me now?” ad campaign from Verizon Wireless has been popular for the past few years. Similarly, those same people will get angry with you if your program “breaks” their phone:
By tying up the CPU so that calls can’t be received
By not quietly fading into the background when a call comes in or needs to be placed, because it does not work properly with the rest of the phone’s operating system
By crashing the phone’s operating system, such as by leaking memory like a sieve Hence, developing programs for a phone is a different experience than developing desktop applications, web sites, or back-end server processes. The tools look different,the frameworks behave differently, and there are more limitations on what you can do with your programs.
What Android tries to do is meet you halfway:
You get a commonly used programming language (Java) with some commonly used libraries (e.g., some Apache Commons APIs), with support for tools you may be used to using (Eclipse).
You get a fairly rigid and separate framework in which your programs need to run so they can be “good citizens” on the phone and not interfere with other programs or the operation of the phone itself.
As you might expect, much of this book deals with that framework and how to write programs that work within its confines and take advantage of its capabilities.
What Androids Are Made Of
When you write a desktop application, you are “master of your own domain.” You launch your main window and any child windows—like dialog boxes—that are needed. From your standpoint, you are your own world, leveraging features supported by the operating system, but largely ignorant of any other program that may be running on the computer at the same time. If you do interact with other programs, it is typically through an API, such as Java Database Connectivity (JDBC), or frameworks atop it, to communicate with MySQL or another database. Android has similar concepts, but packaged differently and structured to make phones more crash-resistant. Here are the main components used in an Android application:
Activities: The building block of the user interface is the activity. You can think of an activity as being the Android analogue for the window or dialog box in a desktop application. While it is possible for activities to not have a user interface, most likely your “headless” code will be packaged in the form of content providers or services.
Content providers: Content providers provide a level of abstraction for any data stored on the device that is accessible by multiple applications. The Android development model encourages you to make your own data available to other applications, as well as your own. Building a content provider lets you do that, while maintaining complete control over how your data is accessed.
Services: Activities and content providers are short-lived and can be shut down at any time. Services, on the other hand, are designed to keep running, if needed, independent of any activity. You might use a service for checking for updates to an RSS feed or to play back music even if the controlling activity is no longer operating.
Intents: Intents are system messages, running around the inside of the device, notifying applications of various events, from hardware state changes (e.g., an SD card was inserted), to incoming data (e.g., an SMS message arrived), to application events (e.g., your activity was launched from the device’s main menu). Not only can you respond to intents, but you can create your own to launch other activities or to let you know when specific situations arise (e.g., raise such-and-so intent when the user gets within 100 meters of this-and-such location).
Stuff at Your Disposal
Android comes with a number of features to help you develop applications: �
Storage: You can package data files with your application, for things that do not change, such as icons or help files. You also can carve out a bit of space on the device itself, for databases or files containing user-entered or retrieved data needed by your application. And, if the user supplies bulk storage, like an SD card, you can read and write files there as needed.
Network: Android devices will generally be Internet-ready, through one communications medium or another. You can take advantage of the Internet access at any level you wish, from raw Java sockets all the way up to a built-in WebKit-based web browser widget you can embed in your application.
Multimedia: Android devices have the ability to play back and record audio and video. While the specifics may vary from device to device, you can query the device to learn its capabilities, and then take advantage of the multimedia capabilities as you see fit—whether that is to play back music, take pictures with the camera, or use the microphone for audio note-taking. Global positioning system (GPS): Android devices will frequently have access to location providers, such as a GPS, which can tell your applications where the device is on the face of the Earth. In turn, you can display maps or otherwise take advantage of the location data, such as tracking a device’s movements if the device has been stolen.
Phone services: Of course, since Android devices are typically phones, your software can initiate calls, send and receive Short Message Service (SMS) messages, and everything else you expect from a modern bit of telephony technology.
Projects and Targets
After you have downloaded and installed the latest Android Software Development Kit (SDK), and perhaps the Android Developer Tools (ADT) plugin for Eclipse (both available from the Android Developers web site), you’re ready to get started. This chapter covers what is involved in building an Android application.
Pieces and Parts
To create an Android application, you will need to create a corresponding Android project. This could be an Eclipse project, if you are using Eclipse for Android development. The project will hold all of your source code, resources (e.g., internationalized strings), third-party JARs, and related materials. The Android build tools—whether Eclipse-integrated or stand-alone—will turn the contents of your project into an Android package (APK) file, which is the Android application. Those tools will also help you get your APK file onto an Android emulator or an actual Android device for testing purposes.
One key element of a project is the manifest (AndroidManifest.xml). This file contains the
“table of contents” for your application, listing all of the major application components,
permissions, and so on. The manifest is used by Android at runtime to tie your application into the operating system. The manifest contents are also used by the Android Market (and perhaps other independent “app stores”), so applications that need Android 2.0 will not be presented to people with Android 1.5 devices, for example. To test your application with the emulator, you will need to create an Android Virtual Device, or AVD. Most likely, you will create several of these, as each AVD emulates an Android device with a particular set of hardware. You might have AVDs for different screen sizes, Android versions, and so on.
When creating projects and creating AVDs, you will need to indicate to Android the API level with which you are working. The API level is a simple integer that maps to an Android version; for example, API level 3 means Android 1.5. When creating a project, you will be able to tell Android the minimum and maximum API levels your application supports. When creating an AVD, you will tell Android which API level the AVD should emulate, so you can see how your application runs on various (fake) devices implementing different versions of Android. All of these concepts are described in greater detail in this chapter.
Creating a Project
To create a project from the command line, for use with the command-line build tools (e.g., ant), you will need to run the Android create project command. This command takes a number of switches to indicate the Java package in which the application’s code will reside, the API level the application is targeting, and so on. The result of running this
command will be a directory containing all of the files necessary to build a “Hello, World!” Android application.
Here is an example of running android create project: android create project --target 2 --path ./FirstApp --activity FirstApp --package apt.tutorial If you intend to develop for Android using Eclipse, rather than Android create project, you will use the Eclipse new-project wizard to create a new Android application.
NOTE: The source code that accompanies this book was set up to be built using the commandline
build tools. If you prefer to use Eclipse, you can create empty Eclipse Android projects and import the code into those projects.
Project Structure
The Android build system is organized around a specific directory tree structure for your Android project, much like any other Java project. The specifics, though, are fairly unique to Android. Here’s a quick primer on the project structure, to help you make sense of it all, particularly for the sample code referenced in this book.
Root Contents
When you create a new Android project (e.g., via android create project), you get several items in the project’s root directory, including the following:
Androidmanifest.xml: An XML file describing the application being built and which components—activities, services, and so on—are being supplied by that application.
build.xml: An Ant script for compiling the application and installing it Defult.properties and local.properties: Property files used by the Ant build script.
assets/: A folder that holds other static files you wish packaged with the application for deployment onto the device.
bin/: A folder that holds the application once it is compiled.
gen/: Where Android’s build tools will place source code that they generate.
lib/: A folder that holds any third-party JARs your application requires.
src/: A folder that holds the Java source code for the application.
Res/: A folder that holds resources—such as icons, graphic user
interface (GUI) layouts, and the like—that are packaged with the compiled Java in the application.
test/: A folder that holds an entirely separate Android project used for testing the one you created.
The Sweat Off Your Brow
When you create an Android project (e.g., via android creat project), you supply the fully qualified class name of the main activity for the application (e.g., com.commonsware.android.SomeDemo). You will then find that your project’s src/ tree already has the namespace directory tree in place, plus a stub Activity subclass representing your main activity (e.g.,src/com/commonsware/android/SomeDemo.java). You are welcome to modify this file and add others to the src/ tree as needed to implement your application. The first time you compile the project (e.g., via ant), out in the main activity’s namespace directory, the Android build chain will create R.java. This contains a number of constants tied to the various resources you placed in the res/ directory tree. Throughout this book, you will see that many of the examples reference things in R.java/ (e.g.,referring to a layout’s identifier via R.layout.main).
NOTE: You should not modify R.java yourself, but instead let the Android tools handle this for you.
And Now, the Rest of the Story
The res/ directory tree holds resources—static files that are packaged along with your
application, either in their original form or, occasionally, in a preprocessed form. These
are some of the subdirectories you will find or create under res/:
res/drawable/ For images (PNG, JPEG, etc.).
res/layout/: For XML-based UI layout specifications.
res/menu/: For XML-based menu specifications.
es/raw/: For general-purpose files (e.g., a CSV file of account information).
res/values/: For strings, dimensions, and the like.
res/xml/: For other general-purpose XML files you wish to ship.
All of these, as well as other resources, are covered in this book.
What You Get Out of It
When you compile your project (via ant or the IDE), the results go into the bin/ directory under your project root, as follows:
bin/classes/: Holds the compiled Java classes.
bin/classes.dex: Holds the executable created from those compiled Java classes.
bin/yourapp.ap: Holds your application’s resources, packaged as a ZIP file (where yourapp is the name of your application).
The .apk file is a ZIP archive containing the .dex file, the compiled edition of your
resources (resowrces.arsc), any uncompiled resources (such as what you put in
res.raw), and the androidmanigest.xml file. It is also digitally signed, with the -debug portion of the filename indicating it has been signed using a debug key that works with
the emulator, or -unsigned indicating that you built your application for release (ant release), but the APK still needs to be signed using jarsigner and an official key.
Inside the Manifest
The foundation for any Android application is the manifest file, androidmanifest.xml in
the root of your project. Here is where you declare what is inside your application—the
activities, the services, and so on. You also indicate how these pieces attach themselves
to the overall Android system; for example, you indicate which activity (or activities)
should appear on the device’s main menu (a.k.a. the launcher).
When you create your application, a starter manifest will be generated for you
automatically. For a simple application, offering a single activity and nothing else, the
autogenerated manifest will probably work out fine, or perhaps require a few minor
modifications. On the other end of the spectrum, the manifest file for the Android API
demo suite is more than 1,000 lines long. Your production Android applications will
probably fall somewhere in the middle.
Most of the interesting bits of the manifest will be described in greater detail in the
chapters on their associated Android features. For example, the service element will be
described in greater detail in Chapter 29, which covers creating services. For now, you
just need to understand the role of the manifest and its general overall construction.
In the Beginning, There Was the Root, And It Was Good
The root of all manifest files is, not surprisingly, a manifest element:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.commonsware.android.search">
...
</manifest>
Note the namespace declaration. Curiously, the generated manifests apply it only on the
attributes, not the elements (e.g., it’s manifest, not android:manifest). Since this pattern
works, unless Android changes, you should stick with it. The biggest piece of information you need to supply on the manifest element is the package attribute (also curiously not namespaced). Here, you can provide the name of the Java package that will be considered the “base” of your application. Then, everywhere else in the manifest file that needs a class name, you can just substitute a leading dot as shorthand for the package. For example, if you needed to refer to com.commonsware.android.search.Snicklefritz in this preceding manifest, you could just use .Snicklefritz since com.commonsware.android.search�is defined as the application’s package.