Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,327
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
100
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Android Mobile Application Development Mr. Pritesh N. Patel Page 1 What is Android? Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language. Features Application framework enabling reuse and replacement of components Dalvik virtual machine optimized for mobile devices Integrated browser based on the open source WebKit engine Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional) SQLite for structured data storage Media support for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, and GIF) GSM Telephony (hardware dependent) Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (hardware dependent) Rich development environment including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE Android Architecture The following diagram shows the major components of the Android operating system. Each section is described in more detail below.
  • 2. Android Mobile Application Development Mr. Pritesh N. Patel Page 2 Applications Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language. Application Framework By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more. Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user. Underlying all applications is a set of services and systems, including: A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser 1. Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data 2. A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files 3. A Notification Manager that enables all applications to display custom alerts in the status bar 4. An Activity Manager that manages the lifecycle of applications and provides a common navigation backstack Libraries Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below: System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
  • 3. Android Mobile Application Development Mr. Pritesh N. Patel Page 3 Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view SGL - the underlying 2D graphics engine 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer FreeType - bitmap and vector font rendering SQLite - a powerful and lightweight relational database engine available to all applications Android Runtime Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool. The Dalvik VM relies on the Linux kernel for underlying functionality such as threading and low-level memory management. Linux Kernel Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack. Quick Start The steps below provide an overview of how to get started with the Android SDK. For detailed instructions, start with the Installing the SDK guide. 1. Prepare your development computer Read the System Requirements document and make sure that your development computer meets the hardware and software requirements for the Android SDK. Install any additional software needed before downloading the Android SDK. In particular, you may need to install the JDK (version 5 or 6 required) and Eclipse (version 3.4 or 3.5, needed only if you want develop using the ADT Plugin).
  • 4. Android Mobile Application Development Mr. Pritesh N. Patel Page 4 2. Download and install the SDK starter package Select a starter package from the table at the top of this page and download it to your development computer. To install the SDK, simply unpack the starter package to a safe location and then add the location to your PATH. 3. Install the ADT Plugin for Eclipse If you are developing in Eclipse, set up a remote update site at https://dl- ssl.google.com/android/eclipse/. Install the Android Development Tools (ADT) Plugin, restart Eclipse, and set the "Android" preferences in Eclipse to point to the SDK install location. 4. Add Android platforms and other components to your SDK Use the Android SDK and AVD Manager, included in the SDK starter package, to add one or more Android platforms (for example, Android 1.6 or Android 2.2) and other components to your SDK. If you aren't sure what to add, see Which components do I need? To launch the Android SDK and AVD Manager on Windows, execute SDK Setup.exe, at the root of the SDK directory. On Mac OS X or Linux, execute the androidtool in the <sdk>/tools/ folder Done! Name Description add-ons/ Contains add-ons to the Android SDK development environment, which let you develop against external libraries that are available on some devices. docs/ A full set of documentation in HTML format, including the Developer's Guide, API Reference, and other information. To read the documentation, load the file offline.html in a web browser. platforms/ Contains a set of Android platform versions that you can develop applications against, each in a separate directory. <platform>/ Platform version directory, for example "android-1.6". All platform version directories contain a similar set of files and subdirectory
  • 5. Android Mobile Application Development Mr. Pritesh N. Patel Page 5 structure. data/ Storage area for default fonts and resource definitions. images/ Storage area for default disk images, including the Android system image, the default userdata image, the default ramdisk image, and more. The images are used in emulator sessions. skins/ A set of emulator skins available for the platform version. Each skin is designed for a specific screen resolution. templates/ Storage area for file templates used by the SDK development tools. tools/ Any development tools that are specific to the platform version. android.jar The Android library used when compiling applications against this platform version. samples/ Sample code and apps that are specific to platform version. tools/ Contains the set of development and profiling tools available to you, such as the emulator, the android tool, adb, ddms, and more. SDK Readme.txt A file that explains how to perform the initial setup of your SDK, including how to launch the Android SDK and AVD Manager tool on all platforms SDK Setup.exe Windows SDK only. A shortcut that launches the Android SDK and AVD Manager tool, which you use to add components to your SDK. Hello, World As a developer, you know that the first impression of a development framework is how easy it is to write "Hello, World." Well, on Android, it's pretty easy. It's particularly easy if you're using Eclipse as your IDE, because we've provided a great plugin that handles your project creation and management to greatly speed-up your development cycles.
  • 6. Android Mobile Application Development Mr. Pritesh N. Patel Page 6 This tutorial assumes that you're using Eclipse. If you're not, see Developing in Other IDEs. You can then return to this tutorial and ignore anything about Eclipse. Before you start, you should already have the SDK installed, and if you're using Eclipse, you should have installed the ADT plugin as well. If you have not installed these, see Installing the Android SDK and return here when you've completed the installation. Install a Platform To run the Hello World application, you need to install at least one Android platform in your SDK environment. If you have not already performed this step, you need to do it now. To install a platform in Eclipse: In the Android SDK and AVD Manager, choose Available Packages in the left panel. Click the repository site checkbox to display the components available for installation. Select at least one platform to install, and click Install Selected. If you aren't sure which platform to install, use the latest version. Create an AVD In this tutorial, you will run your application in the Android Emulator. Before you can launch the emulator, you must create an Android Virtual Device (AVD). An AVD defines the system image and device settings used by the emulator. To create an AVD: In Eclipse, choose Window > Android SDK and AVD Manager. Select Virtual Devices in the left panel. Click New. The Create New AVD dialog appears. Type the name of the AVD, such as "my_avd". Choose a target. The target is the platform (that is, the version of the Android SDK, such as 2.1) you want to run on the emulator. You can ignore the rest of the fields for now. Click Create AVD. Create a New Android Project After you've created an AVD, the next step is to start a new Android project in Eclipse. From Eclipse, select File > New > Project. If the ADT Plugin for Eclipse has been successfully installed, the resulting dialog should have a folder labeled "Android" which should contain "Android Project". (After you create one or more Android projects, an entry for "Android XML File" will also be available.)
  • 7. Android Mobile Application Development Mr. Pritesh N. Patel Page 7 Select "Android Project" and click Next. Fill in the project details with the following values: Project name: HelloAndroid Application name: Hello, Android Package name: com.example.helloandroid (or your own private namespace) Create Activity: HelloAndroid Click Finish.
  • 8. Android Mobile Application Development Mr. Pritesh N. Patel Page 8 Here is a description of each field: Project Name
  • 9. Android Mobile Application Development Mr. Pritesh N. Patel Page 9 This is the Eclipse Project name — the name of the directory that will contain the project files. Application Name This is the human-readable title for your application — the name that will appear on the Android device. Package Name This is the package namespace (following the same rules as for packages in the Java programming language) that you want all your source code to reside under. This also sets the package name under which the stub Activity will be generated. Your package name must be unique across all packages installed on the Android system; for this reason, it's important to use a standard domain-style package for your applications. The example above uses the "com.example" namespace, which is a namespace reserved for example documentation — when you develop your own applications, you should use a namespace that's appropriate to your organization or entity. Create Activity This is the name for the class stub that will be generated by the plugin. This will be a subclass of Android's Activity class. An Activity is simply a class that can run and do work. It can create a UI if it chooses, but it doesn't need to. As the checkbox suggests, this is optional, but an Activity is almost always used as the basis for an application. Min SDK Version This value specifies the minimum API Level required by your application. For more information, see Android API Levels. Other fields: The checkbox for "Use default location" allows you to change the location on disk where the project's files will be generated and stored. "Build Target" is the platform target that your application will be compiled against (this should be selected automatically, based on your Min SDK Version). Notice that the "Build Target" you've selected uses the Android 1.1 platform. This means that your application will be compiled against the Android 1.1 platform library. If you recall, the AVD created above runs on the Android 1.5 platform. These don't have to match; Android applications are forward-compatible, so an application built against the 1.1 platform library will run normally on the 1.5 platform. The reverse is not true.
  • 10. Android Mobile Application Development Mr. Pritesh N. Patel Page 10 Your Android project is now ready. It should be visible in the Package Explorer on the left. Open the HelloAndroid.java file, located inside HelloAndroid > src > com.example.helloandroid). It should look like this: package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } Notice that the class is based on the Activity class. An Activity is a single application entity that is used to perform actions. An application may have many separate activities, but the user interacts with them one at a time. The onCreate() method will be called by the Android system when your Activity starts — it is where you should perform all initialization and UI setup. An activity is not required to have a user interface, but usually will. Now let's modify some code! Construct the UI Take a look at the revised code below and then make the same changes to your HelloAndroid class. The bold items are lines that have been added. package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
  • 11. Android Mobile Application Development Mr. Pritesh N. Patel Page 11 TextView tv = new TextView(this); tv.setText("Hello, Android"); setContentView(tv); } } Tip: An easy way to add import packages to your project is to press Ctrl-Shift-O (Cmd- Shift-O, on Mac). This is an Eclipse shortcut that identifies missing packages based on your code and adds them for you. An Android user interface is composed of hierarchies of objects called Views. A View is a drawable object used as an element in your UI layout, such as a button, image, or (in this case) a text label. Each of these objects is a subclass of the View class and the subclass that handles text is TextView. In this change, you create a TextView with the class constructor, which accepts an Android Context instance as its parameter. A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. The Activity class inherits from Context, and because your HelloAndroid class is a subclass of Activity, it is also a Context. So, you can pass this as your Context reference to the TextView. Next, you define the text content with setText(). Finally, you pass the TextView to setContentView() in order to display it as the content for the Activity UI. If your Activity doesn't call this method, then no UI is present and the system will display a blank screen. There it is — "Hello, World" in Android! The next step, of course, is to see it running. Run the Application The Eclipse plugin makes it easy to run your applications: Select Run > Run. Select "Android Application". To learn more about creating and editing run configurations in Eclipse, refer to Developing In Eclipse, with ADT. The Eclipse plugin automatically creates a new run configuration for your project and then launches the Android Emulator. Depending on your environment, the Android emulator might take several minutes to boot fully, so please be patient. When the emulator is booted,
  • 12. Android Mobile Application Development Mr. Pritesh N. Patel Page 12 the Eclipse plugin installs your application and launches the default Activity. You should now see something like this: The "Hello, Android" you see in the grey bar is actually the application title. The Eclipse plugin creates this automatically (the string is defined in theres/values/strings.xml file and referenced by your AndroidManifest.xml file). The text below the title is the actual text that you have created in the TextView object. That concludes the basic "Hello World" tutorial, but you should continue reading for some more valuable information about developing Android applications. 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 easy to forget to properly connect Views together, which can result in errors in your layout and wasted time debugging your code. That's why Android provides an alternate UI construction model: XML-based layout files. The easiest way to explain this concept is to show an example. Here's an XML layout file that is identical in behavior to the programmatically-constructed example:
  • 13. Android Mobile Application Development Mr. Pritesh N. Patel Page 13 <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello"/> The general structure of an Android XML layout file is simple: it's a tree of XML elements, wherein each node is the name of a View class (this example, however, is just one View element). You can use the name of any class that extends View as an element in your XML layouts, including custom View classes you define in your own code. This structure makes it easy to quickly build up UIs, using a more simple structure and syntax than you would use in a programmatic layout. This model is inspired by the web development model, wherein you can separate the presentation of your application (its UI) from the application logic used to fetch and fill in data. In the above XML example, there's just one View element: the TextView, which has five XML attributes. Here's a summary of what they mean: Attribute Meaning xmlns:android This is an XML namespace declaration that tells the Android tools that you are going to refer to common attributes defined in the Android namespace. The outermost tag in every Android layout file must have this attribute. android:id This attribute assigns a unique identifier to the TextView element. You can use the assigned ID to reference this View from your source code or from other XML resource declarations. android:layout_width This attribute defines how much of the available width on the screen this View should consume. In this case, it's the only View so you want it to take up the entire screen, which is what a value of "fill_parent" means. android:layout_height This is just like android:layout_width, except that it refers to available screen height. android:text This sets the text that the TextView should display. In this example, you use a string resource instead of a hard-coded string value. The hello string is defined in
  • 14. Android Mobile Application Development Mr. Pritesh N. Patel Page 14 the res/values/strings.xml file. This is the recommended practice for inserting strings to your application, because it makes the localization of your application to other languages graceful, without need to hard-code changes to the layout file. For more information, see Resources and Internationalization. These XML layout files belong in the res/layout/ directory of your project. The "res" is short for "resources" and the directory contains all the non-code assets that your application requires. In addition to layout files, resources also include assets such as images, sounds, and localized strings. Landscape layout When you want a different design for landscape, put your layout XML file inside /res/layout-land. Android will automatically look here when the layout changes. Without this special landscape layout defined, Android will stretch the default layout. The Eclipse plugin automatically creates one of these layout files for you: main.xml. In the "Hello World" application you just completed, this file was ignored and you created a layout programmatically. This was meant to teach you more about the Android framework, but you should almost always define your layout in an XML file instead of in your code. The following procedures will instruct you how to change your existing application to use an XML layout. In the Eclipse Package Explorer, expand the /res/layout/ folder and open main.xml (once opened, you might need to click the "main.xml" tab at the bottom of the window to see the XML source). Replace the contents with the following XML: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/hello"/> Save the file. Inside the res/values/ folder, open strings.xml. This is where you should save all default text strings for your user interface. If you're using Eclipse, then ADT will have started you with two strings, hello and app_name. Revise hello to something else. Perhaps "Hello, Android! I am a string resource!" The entire file should now look like this:
  • 15. Android Mobile Application Development Mr. Pritesh N. Patel Page 15 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello, Android! I am a string resource!</string> <string name="app_name">Hello, Android</string> </resources> Now open and modify your HelloAndroid class use the XML layout. Edit the file to look like this: package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } When you make this change, type it by hand to try the code-completion feature. As you begin typing "R.layout.main" the plugin will offer you suggestions. You'll find that it helps in a lot of situations. Instead of passing setContentView() a View object, you give it a reference to the layout resource. The resource is identified as R.layout.main, which is actually a compiled object representation of the layout defined in /res/layout/main.xml. The Eclipse plugin automatically creates this reference for you inside the project's R.java class. If you're not using Eclipse, then the R.java class will be generated for you when you run Ant to build the application. (More about the R class in a moment.) Now re-run your application — because you've created a launch configuration, all you need to do is click the green arrow icon to run, or select Run > Run History > Android Activity. Other than the change to the TextView string, the application looks the same. After all, the point was to show that the two different layout approaches produce identical results. Tip: Use the shortcut Ctrl-F11 (Cmd-Shift-F11, on Mac) to run your currently visible application.
  • 16. Android Mobile Application Development Mr. Pritesh N. Patel Page 16 Continue reading for an introduction to debugging and a little more information on using other IDEs. When you're ready to learn more, read Application Fundamentals for an introduction to all the elements that make Android applications work. Also refer to the Developer's Guide introduction page for an overview of the Dev Guide documentation. R class In Eclipse, open the file named R.java (in the gen/ [Generated Java Files] folder). It should look something like this: package com.example.helloandroid; public final class R { public static final class attr { } public static final class drawable { public static final int icon=0x7f020000; } public static final class id { public static final int textview=0x7f050000; } public static final class layout { public static final int main=0x7f030000; } public static final class string { public static final int app_name=0x7f040001; public static final int hello=0x7f040000; } } A project's R.java file is an index into all the resources defined in the file. You use this class in your source code as a sort of short-hand way to refer to resources you've included in your project. This is particularly powerful with the code-completion features of IDEs like Eclipse because it lets you quickly and interactively locate the specific reference you're looking for. It's possible yours looks slighly different than this (perhaps the hexadecimal values are different). For now, notice the inner class named "layout", and its member field "main". The Eclipse plugin noticed the XML layout file named main.xml and generated a class for it here. As you add other resources to your project (such as strings in the res/values/string.xml file or drawables inside the res/drawable/ direcory) you'll see R.java change to keep up.
  • 17. Android Mobile Application Development Mr. Pritesh N. Patel Page 17 When not using Eclipse, this class file will be generated for you at build time (with the Ant tool). You should never edit this file by hand. Debug Your Project The Android Plugin for Eclipse also has excellent integration with the Eclipse debugger. To demonstrate this, introduce a bug into your code. Change your HelloAndroid source code to look like this: package com.example.helloandroid; import android.app.Activity; import android.os.Bundle; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Object o = null; o.toString(); setContentView(R.layout.main); } } This change simply introduces a NullPointerException into your code. If you run your application again, you'll eventually see this:
  • 18. Android Mobile Application Development Mr. Pritesh N. Patel Page 18 Press "Force Quit" to terminate the application and close the emulator window. To find out more about the error, set a breakpoint in your source code on the line Object o = null; (double-click on the marker bar next to the source code line). Then select Run > Debug History > Hello, Android from the menu to enter debug mode. Your app will restart in the emulator, but this time it will suspend when it reaches the breakpoint you set. You can then step through the code in Eclipse's Debug Perspective, just as you would for any other application. Creating the Project without Eclipse If you don't use Eclipse (such as if you prefer another IDE, or simply use text editors and command line tools) then the Eclipse plugin can't help you. Don't worry though — you don't lose any functionality just because you don't use Eclipse. The Android Plugin for Eclipse is really just a wrapper around a set of tools included with the Android SDK. (These tools, like the emulator, aapt, adb, ddms, and others are documented elsewhere.) Thus, it's possible to wrap those tools with another tool, such as an 'ant' build file. The Android SDK includes a tool named "android" that can be used to create all the source code and directory stubs for your project, as well as an ant-compatiblebuild.xml file. This allows you to build your project from the command line, or integrate it with the IDE of your choice. For example, to create a HelloAndroid project similar to the one created in Eclipse, use this command:
  • 19. Android Mobile Application Development Mr. Pritesh N. Patel Page 19 android create project --package com.example.helloandroid --activity HelloAndroid --target 2 --path <path-to-your-project>/HelloAndroid This creates the required folders and files for the project at the location defined by the path. 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 application lives in its own world: By default, every application runs in its own Linux process. Android starts the process when any of the application's code needs to be executed, and shuts down the process when it's no longer needed and system resources are required by other applications. Each process has its own virtual machine (VM), so application code runs in isolation from the code of all other applications. By default, each application is assigned a unique Linux user ID. Permissions are set so that the application's files are visible only to that user and only to the application itself — although there are ways to export them to other applications as well. It's possible to arrange for two applications to share the same user ID, in which case they will be able to see each other's files. To conserve system resources, applications with the same ID can also arrange to run in the same Linux process, sharing the same VM. 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 up that piece of the other application when the need arises.
  • 20. Android Mobile Application Development Mr. Pritesh N. Patel Page 20 For this to work, the system must be able to start an application process when any part of it is needed, and instantiate the Java objects for that part. Therefore, unlike applications on most other systems, Android applications don't have a single entry point for everything in the application (no main() function, for example). Rather, they have essential components that the system can instantiate and run as needed. There are four types of components: Activities An activity presents a visual user interface for one focused endeavor the user can undertake. For example, an activity might present a list of menu items users can choose from or it might display photographs along with their captions. A text messaging application might have one activity that shows a list of contacts to send messages to, a second activity to write the message to the chosen contact, and other activities to review old messages or change settings. Though they work together to form a cohesive user interface, each activity is independent of the others. Each one is implemented as a subclass of the Activity base class. An application might consist of just one activity or, like the text messaging application just mentioned, it may contain several. What the activities are, and how many there are depends, of course, on the application and its design. Typically, one of the activities is marked as the first one that should be presented to the user when the application is launched. Moving from one activity to another is accomplished by having the current activity start the next one. Each activity is given a default window to draw in. Typically, the window fills the screen, but it might be smaller than the screen and float on top of other windows. An activity can also make use of additional windows — for example, a pop-up dialog that calls for a user response in the midst of the activity, or a window that presents users with vital information when they select a particular item on-screen. The visual content of the window is provided by a hierarchy of views — objects derived from the base View class. Each view controls a particular rectangular space within the window. Parent views contain and organize the layout of their children. Leaf views (those at the bottom of the hierarchy) draw in the rectangles they control and respond to user actions directed at that space. Thus, views are where the activity's interaction with the user takes place. For example, a view might display a small image and initiate an action when the user taps that image. Android has a number of ready-made views that you can use — including buttons, text fields, scroll bars, menu items, check boxes, and more. A view hierarchy is placed within an activity's window by the Activity.setContentView() method. The content view is the View object at the root
  • 21. Android Mobile Application Development Mr. Pritesh N. Patel Page 21 of the hierarchy. (See the separate User Interface document for more information on views and the hierarchy.) Services A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it. Each service extends the Service base class. A prime example is a media player playing songs from a play list. The player application would probably have one or more activities that allow the user to choose songs and start playing them. However, the music playback itself would not be handled by an activity because users will expect the music to keep playing even after they leave the player and begin something different. To keep the music going, the media player activity could start a service to run in the background. The system would then keep the music playback service running even after the activity that started it leaves the screen. It's possible to connect to (bind to) an ongoing service (and start the service if it's not already running). While connected, you can communicate with the service through an interface that the service exposes. For the music service, this interface might allow users to pause, rewind, stop, and restart the playback. Like activities and the other components, services run in the main thread of the application process. So that they won't block other components or the user interface, they often spawn another thread for time-consuming tasks (like music playback). See Processes and Threads, later. Broadcast receivers A broadcast receiver is a component that does nothing but receive and react to broadcast announcements. Many broadcasts originate in system code — for example, announcements that the timezone has changed, that the battery is low, that a picture has been taken, or that the user changed a language preference. Applications can also initiate broadcasts — for example, to let other applications know that some data has been downloaded to the device and is available for them to use. An application can have any number of broadcast receivers to respond to any announcements it considers important. All receivers extend the BroadcastReceiverbase class. Broadcast receivers do not display a user interface. However, they may start an activity in response to the information they receive, or they may use
  • 22. Android Mobile Application Development Mr. Pritesh N. Patel Page 22 theNotificationManager to alert the user. Notifications can get the user's attention in various ways — flashing the backlight, vibrating the device, playing a sound, and so on. They typically place a persistent icon in the status bar, which users can open to get the message. Content providers A content provider makes a specific set of the application's data available to other applications. The data can be stored in the file system, in an SQLite database, or in any other manner that makes sense. The content provider extends the ContentProvider base class to implement a standard set of methods that enable other applications to retrieve and store data of the type it controls. However, applications do not call these methods directly. Rather they use a ContentResolver object and call its methods instead. A ContentResolver can talk to any content provider; it cooperates with the provider to manage any interprocess communication that's involved. See the separate Content Providers document for more information on using content providers. Whenever there's a request that should be handled by a particular component, Android makes sure that the application process of the component is running, starting it if necessary, and that an appropriate instance of the component is available, creating the instance if necessary. Activating components: intents Content providers are activated when they're targeted by a request from a ContentResolver. The other three components — activities, services, and broadcast receivers — are activated by asynchronous messages called intents. An intent is an Intent object that holds the content of the message. For activities and services, it names the action being requested and specifies the URI of the data to act on, among other things. For example, it might convey a request for an activity to present an image to the user or let the user edit some text. For broadcast receivers, the Intent object names the action being announced. For example, it might announce to interested parties that the camera button has been pressed. There are separate methods for activating each type of component: An activity is launched (or given something new to do) by passing an Intent object to Context.startActivity() orActivity.startActivityForResult(). The responding activity can look at the initial intent that caused it to be launched by calling its getIntent() method. Android calls the activity's onNewIntent() method to pass it any subsequent intents. One activity often starts the next one. If it expects a result back from the activity it's starting, it calls startActivityForResult() instead ofstartActivity(). For example, if it starts an
  • 23. Android Mobile Application Development Mr. Pritesh N. Patel Page 23 activity that lets the user pick a photo, it might expect to be returned the chosen photo. The result is returned in an Intent object that's passed to the calling activity's onActivityResult() method. A service is started (or new instructions are given to an ongoing service) by passing an Intent object to Context.startService(). Android calls the service'sonStart() method and passes it the Intent object. Similarly, an intent can be passed to Context.bindService() to establish an ongoing connection between the calling component and a target service. The service receives the Intent object in an onBind() call. (If the service is not already running, bindService() can optionally start it.) For example, an activity might establish a connection with the music playback service mentioned earlier so that it can provide the user with the means (a user interface) for controlling the playback. The activity would call bindService() to set up that connection, and then call methods defined by the service to affect the playback. A later section, Remote procedure calls, has more details about binding to a service. An application can initiate a broadcast by passing an Intent object to methods like Context.sendBroadcast(), Context.sendOrderedBroadcast(), andContext.sendStickyBroadcast() in any of their variations. Android delivers the intent to all interested broadcast receivers by calling their onReceive()methods. For more on intent messages, see the separate article, Intents and Intent Filters. Shutting down components A content provider is active only while it's responding to a request from a ContentResolver. And a broadcast receiver is active only while it's responding to a broadcast message. So there's no need to explicitly shut down these components. Activities, on the other hand, provide the user interface. They're in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues. Similarly, services may also remain running for a long time. So Android has methods to shut down activities and services in an orderly way: An activity can be shut down by calling its finish() method. One activity can shut down another activity (one it started with startActivityForResult()) by calling finishActivity(). A service can be stopped by calling its stopSelf() method, or by calling Context.stopService(). Components might also be shut down by the system when they are no longer being used or when Android must reclaim memory for more active components. A later section, Component Lifecycles, discusses this possibility and its ramifications in more detail.
  • 24. Android Mobile Application Development Mr. Pritesh N. Patel Page 24 The manifest file Before Android can start an application component, it must learn that the component exists. Therefore, applications declare their components in a manifest file that's bundled into the Android package, the .apk file that also holds the application's code, files, and resources. The manifest is a structured XML file and is always named AndroidManifest.xml for all applications. It does a number of things in addition to declaring the application's components, such as naming any libraries the application needs to be linked against (besides the default Android library) and identifying any permissions the application expects to be granted. But the principal task of the manifest is to inform Android about the application's components. For example, an activity might be declared as follows: <?xml version="1.0" encoding="utf-8"?> <manifest . . . > <application . . . > <activity android:name="com.example.project.FreneticActivity" android:icon="@drawable/small_pic.png" android:label="@string/freneticLabel" . . . > </activity> . . . </application> </manifest> The name attribute of the <activity> element names the Activity subclass that implements the activity. The icon and label attributes point to resource files containing an icon and label that can be displayed to users to represent the activity. The other components are declared in a similar way — <service> elements for services, <receiver> elements for broadcast receivers, and <provider> elements for content providers. Activities, services, and content providers that are not declared in the manifest are not visible to the system and are consequently never run. However, broadcast receivers can either be declared in the manifest, or they can be created dynamically in code (as BroadcastReceiver objects) and registered with the system by calling Context.registerReceiver(). For more on how to structure a manifest file for your application, see The AndroidManifest.xml File.
  • 25. Android Mobile Application Development Mr. Pritesh N. Patel Page 25 Intent filters An Intent object can explicitly name a target component. If it does, Android finds that component (based on the declarations in the manifest file) and activates it. But if a target is not explicitly named, Android must locate the best component to respond to the intent. It does so by comparing the Intent object to the intent filters of potential targets. A component's intent filters inform Android of the kinds of intents the component is able to handle. Like other essential information about the component, they're declared in the manifest file. Here's an extension of the previous example that adds two intent filters to the activity: <?xml version="1.0" encoding="utf-8"?> <manifest . . . > <application . . . > <activity android:name="com.example.project.FreneticActivity" android:icon="@drawable/small_pic.png" android:label="@string/freneticLabel" . . . > <intent-filter . . . > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter . . . > <action android:name="com.example.project.BOUNCE" /> <data android:mimeType="image/jpeg" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> . . . </application> </manifest> The first filter in the example — the combination of the action "android.intent.action.MAIN" and the category "android.intent.category.LAUNCHER" — is a common one. It marks the activity as one that should be represented in the application launcher, the screen listing applications users can launch on the device. In other words, the activity is the entry point for the application, the initial one users would see when they choose the application in the launcher. The second filter declares an action that the activity can perform on a particular type of data.
  • 26. Android Mobile Application Development Mr. Pritesh N. Patel Page 26 A component can have any number of intent filters, each one declaring a different set of capabilities. If it doesn't have any filters, it can be activated only by intents that explicitly name the component as the target. For a broadcast receiver that's created and registered in code, the intent filter is instantiated directly as an IntentFilter object. All other filters are set up in the manifest. Activities and Tasks As noted earlier, one activity can start another, including one defined in a different application. Suppose, for example, that you'd like to let users display a street map of some location. There's already an activity that can do that, so all your activity needs to do is put together an Intent object with the required information and pass it tostartActivity(). The map viewer will display the map. When the user hits the BACK key, your activity will reappear on screen. To the user, it will seem as if the map viewer is part of the same application as your activity, even though it's defined in another application and runs in that application's process. Android maintains this user experience by keeping both activities in the same task. Simply put, a task is what the user experiences as an "application." It's a group of related activities, arranged in a stack. The root activity in the stack is the one that began the task — typically, it's an activity the user selected in the application launcher. The activity at the top of the stack is one that's currently running — the one that is the focus for user actions. When one activity starts another, the new activity is pushed on the stack; it becomes the running activity. The previous activity remains in the stack. When the user presses the BACK key, the current activity is popped from the stack, and the previous one resumes as the running activity. The stack contains objects, so if a task has more than one instance of the same Activity subclass open — multiple map viewers, for example — the stack has a separate entry for each instance. Activities in the stack are never rearranged, only pushed and popped. A task is a stack of activities, not a class or an element in the manifest file. So there's no way to set values for a task independently of its activities. Values for the task as a whole are set in the root activity. For example, the next section will talk about the "affinity of a task"; that value is read from the affinity set for the task's root activity. All the activities in a task move together as a unit. The entire task (the entire activity stack) can be brought to the foreground or sent to the background. Suppose, for instance, that the current task has four activities in its stack — three under the current activity. The user presses the HOME key, goes to the application launcher, and selects a new application (actually, a new task). The current task goes into the background and the root activity for the new task is displayed. Then, after a short period, the user goes back to the home screen
  • 27. Android Mobile Application Development Mr. Pritesh N. Patel Page 27 and again selects the previous application (the previous task). That task, with all four activities in the stack, comes forward. When the user presses the BACK key, the screen does not display the activity the user just left (the root activity of the previous task). Rather, the activity on the top of the stack is removed and the previous activity in the same task is displayed. The behavior just described is the default behavior for activities and tasks. But there are ways to modify almost all aspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that started the activity and attributes set in the activity's<activity> element in the manifest. Both requester and respondent have a say in what happens. In this regard, the principal Intent flags are: FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_RESET_TASK_IF_NEEDED FLAG_ACTIVITY_SINGLE_TOP The principal <activity> attributes are: taskAffinity launchMode allowTaskReparenting clearTaskOnLaunch alwaysRetainTaskState finishOnTaskLaunch The following sections describe what some of these flags and attributes do, how they interact, and what considerations should govern their use. Affinities and new tasks By default, all the activities in an application have an affinity for each other — that is, there's a preference for them all to belong to the same task. However, an individual affinity can be set for each activity with the taskAffinity attribute of the <activity> element. Activities defined in different applications can share an affinity, or activities defined in the same application can be assigned different affinities. The affinity comes into play in two circumstances: When the Intent object that launches an activity contains the FLAG_ACTIVITY_NEW_TASK flag, and when an activity has its allowTaskReparenting attribute set to "true". The FLAG_ACTIVITY_NEW_TASK flag
  • 28. Android Mobile Application Development Mr. Pritesh N. Patel Page 28 As described earlier, a new activity is, by default, launched into the task of the activity that called startActivity(). It's pushed onto the same stack as the caller. However, if the Intent object passed to startActivity() contains the FLAG_ACTIVITY_NEW_TASK flag, the system looks for a different task to house the new activity. Often, as the name of the flag implies, it's a new task. However, it doesn't have to be. If there's already an existing task with the same affinity as the new activity, the activity is launched into that task. If not, it begins a new task. The allowTaskReparenting attribute If an activity has its allowTaskReparenting attribute set to "true", it can move from the task it starts in to the task it has an affinity for when that task comes to the fore. For example, suppose that an activity that reports weather conditions in selected cities is defined as part of a travel application. It has the same affinity as other activities in the same application (the default affinity) and it allows reparenting. One of your activities starts the weather reporter, so it initially belongs to the same task as your activity. However, when the travel application next comes forward, the weather reporter will be reassigned to and displayed with that task. If an .apk file contains more than one "application" from the user's point of view, you will probably want to assign different affinities to the activities associated with each of them. Launch modes There are four different launch modes that can be assigned to an <activity> element's launchMode attribute: "standard" (the default mode) "singleTop" "singleTask" "singleInstance" The modes differ from each other on these four points: Which task will hold the activity that responds to the intent. For the "standard" and "singleTop" modes, it's the task that originated the intent (and calledstartActivity()) — unless the Intent object contains the FLAG_ACTIVITY_NEW_TASK flag. In that case, a different task is chosen as described in the previous section, Affinities and new tasks. In contrast, the "singleTask" and "singleInstance" modes mark activities that are always at the root of a task. They define a task; they're never launched into another task. Whether there can be multiple instances of the activity. A "standard" or "singleTop" activity can be instantiated many times. They can belong to multiple tasks, and a given task can have multiple instances of the same activity.
  • 29. Android Mobile Application Development Mr. Pritesh N. Patel Page 29 In contrast, "singleTask" and "singleInstance" activities are limited to just one instance. Since these activities are at the root of a task, this limitation means that there is never more than a single instance of the task on the device at one time. Whether the instance can have other activities in its task. A "singleInstance" activity stands alone as the only activity in its task. If it starts another activity, that activity will be launched into a different task regardless of its launch mode — as if FLAG_ACTIVITY_NEW_TASK was in the intent. In all other respects, the "singleInstance" mode is identical to "singleTask". The other three modes permit multiple activities to belong to the task. A "singleTask" activity will always be the root activity of the task, but it can start other activities that will be assigned to its task. Instances of "standard" and "singleTop" activities can appear anywhere in a stack. Whether a new instance of the class will be launched to handle a new intent. For the default "standard" mode, a new instance is created to respond to every new intent. Each instance handles just one intent. For the "singleTop" mode, an existing instance of the class is re-used to handle a new intent if it resides at the top of the activity stack of the target task. If it does not reside at the top, it is not re-used. Instead, a new instance is created for the new intent and pushed on the stack. For example, suppose a task's activity stack consists of root activity A with activities B, C, and D on top in that order, so the stack is A-B-C-D. An intent arrives for an activity of type D. If D has the default "standard" launch mode, a new instance of the class is launched and the stack becomes A-B-C-D-D. However, if D's launch mode is "singleTop", the existing instance is expected to handle the new intent (since it's at the top of the stack) and the stack remains A-B-C-D. If, on the other hand, the arriving intent is for an activity of type B, a new instance of B would be launched no matter whether B's mode is "standard" or "singleTop" (since B is not at the top of the stack), so the resulting stack would be A-B-C-D-B. As noted above, there's never more than one instance of a "singleTask" or "singleInstance" activity, so that instance is expected to handle all new intents. A "singleInstance" activity is always at the top of the stack (since it is the only activity in the task), so it is always in position to handle the intent. However, a "singleTask" activity may or may not have other activities above it in the stack. If it does, it is not in position to handle the intent, and the intent is dropped. (Even though the intent is dropped, its arrival would have caused the task to come to the foreground, where it would remain.) When an existing activity is asked to handle a new intent, the Intent object is passed to the activity in an onNewIntent() call. (The intent object that originally started the activity can be retrieved by calling getIntent().)
  • 30. Android Mobile Application Development Mr. Pritesh N. Patel Page 30 Note that when a new instance of an Activity is created to handle a new intent, the user can always press the BACK key to return to the previous state (to the previous activity). But when an existing instance of an Activity handles a new intent, the user cannot press the BACK key to return to what that instance was doing before the new intent arrived. For more on launch modes, see the description of the <activity> element. Clearing the stack If the user leaves a task for a long time, the system clears the task of all activities except the root activity. When the user returns to the task again, it's as the user left it, except that only the initial activity is present. The idea is that, after a time, users will likely have abandoned what they were doing before and are returning to the task to begin something new. That's the default. There are some activity attributes that can be used to control this behavior and modify it: The alwaysRetainTaskState attribute If this attribute is set to "true" in the root activity of a task, the default behavior just described does not happen. The task retains all activities in its stack even after a long period. The clearTaskOnLaunch attribute If this attribute is set to "true" in the root activity of a task, the stack is cleared down to the root activity whenever the user leaves the task and returns to it. In other words, it's the polar opposite of alwaysRetainTaskState. The user always returns to the task in its initial state, even after a momentary absence. The finishOnTaskLaunch attribute This attribute is like clearTaskOnLaunch, but it operates on a single activity, not an entire task. And it can cause any activity to go away, including the root activity. When it's set to "true", the activity remains part of the task only for the current session. If the user leaves and then returns to the task, it no longer is present. There's another way to force activities to be removed from the stack. If an Intent object includes the FLAG_ACTIVITY_CLEAR_TOP flag, and the target task already has an instance of the type of activity that should handle the intent in its stack, all activities above that instance are cleared away so that it stands at the top of the stack and can respond to the intent. If the launch mode of the designated activity is "standard", it too will be removed from the stack, and a new instance will be launched to handle the incoming intent. That's because a new instance is always created for a new intent when the launch mode is "standard".
  • 31. Android Mobile Application Development Mr. Pritesh N. Patel Page 31 FLAG_ACTIVITY_CLEAR_TOP is most often used in conjunction with FLAG_ACTIVITY_NEW_TASK. When used together, these flags are a way of locating an existing activity in another task and putting it in a position where it can respond to the intent. Starting tasks An activity is set up as the entry point for a task by giving it an intent filter with "android.intent.action.MAIN" as the specified action and "android.intent.category.LAUNCHER" as the specified category. (There's an example of this type of filter in the earlier Intent Filters section.) A filter of this kind causes an icon and label for the activity to be displayed in the application launcher, giving users a way both to launch the task and to return to it at any time after it has been launched. This second ability is important: Users must be able to leave a task and then come back to it later. For this reason, the two launch modes that mark activities as always initiating a task, "singleTask" and "singleInstance", should be used only when the activity has a MAIN and LAUNCHER filter. Imagine, for example, what could happen if the filter is missing: An intent launches a "singleTask" activity, initiating a new task, and the user spends some time working in that task. The user then presses the HOME key. The task is now ordered behind and obscured by the home screen. And, because it is not represented in the application launcher, the user has no way to return to it. A similar difficulty attends the FLAG_ACTIVITY_NEW_TASK flag. If this flag causes an activity to begin a new task and the user presses the HOME key to leave it, there must be some way for the user to navigate back to it again. Some entities (such as the notification manager) always start activities in an external task, never as part of their own, so they always put FLAG_ACTIVITY_NEW_TASK in the intents they pass to startActivity(). If you have an activity that can be invoked by an external entity that might use this flag, take care that the user has a independent way to get back to the task that's started. For those cases where you don't want the user to be able to return to an activity, set the <activity> element's finishOnTaskLaunch to "true". Processes and Threads When the first of an application's components needs to be run, Android starts a Linux process for it with a single thread of execution. By default, all components of the application run in that process and thread. However, you can arrange for components to run in other processes, and you can spawn additional threads for any process.
  • 32. Android Mobile Application Development Mr. Pritesh N. Patel Page 32 Processes The process where a component runs is controlled by the manifest file. The component elements — <activity>, <service>, <receiver>, and <provider> — each have a process attribute that can specify a process where that component should run. These attributes can be set so that each component runs in its own process, or so that some components share a process while others do not. They can also be set so that components of different applications run in the same process — provided that the applications share the same Linux user ID and are signed by the same authorities. The <application> element also has a process attribute, for setting a default value that applies to all components. All components are instantiated in the main thread of the specified process, and system calls to the component are dispatched from that thread. Separate threads are not created for each instance. Consequently, methods that respond to those calls — methods like View.onKeyDown() that report user actions and the lifecycle notifications discussed later in the Component Lifecycles section — always run in the main thread of the process. This means that no component should perform long or blocking operations (such as networking operations or computation loops) when called by the system, since this will block any other components also in the process. You can spawn separate threads for long operations, as discussed under Threads, next. Android may decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. Application components running in the process are consequently destroyed. A process is restarted for those components when there's again work for them to do. When deciding which processes to terminate, Android weighs their relative importance to the user. For example, it more readily shuts down a process with activities that are no longer visible on screen than a process with visible activities. The decision whether to terminate a process, therefore, depends on the state of the components running in that process. Threads Even though you may confine your application to a single process, there will likely be times when you will need to spawn a thread to do some background work. Since the user interface must always be quick to respond to user actions, the thread that hosts an activity should not also host time-consuming operations like network downloads. Anything that may not be completed quickly should be assigned to a different thread. Threads are created in code using standard Java Thread objects. Android provides a number of convenience classes for managing threads — Looper for running a message loop within a thread, Handler for processing messages, and HandlerThread for setting up a thread with a message loop.
  • 33. Android Mobile Application Development Mr. Pritesh N. Patel Page 33 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 opposite direction. Android provides all the code to do that work, so that you can concentrate on defining and implementing the RPC interface itself. An RPC interface can include only methods. By default, all methods are executed synchronously (the local method blocks until the remote method finishes), even if there is no return value. In brief, the mechanism works as follows: You'd begin by declaring the RPC interface you want to implement using a simple IDL (interface definition language). From that declaration, the aidl tool generates a Java interface definition that must be made available to both the local and the remote process. It contains two inner class, as shown in the following diagram: The inner classes have all the code needed to administer remote procedure calls for the interface you declared with the IDL. Both inner classes implement the IBinderinterface. One of them is used locally and internally by the system; the code you write can ignore it.
  • 34. Android Mobile Application Development Mr. Pritesh N. Patel Page 34 The other, called Stub, extends the Binder class. In addition to internal code for effectuating the IPC calls, it contains declarations for the methods in the RPC interface you declared. You would subclass Stub to implement those methods, as indicated in the diagram. Typically, the remote process would be managed by a service (because a service can inform the system about the process and its connections to other processes). It would have both the interface file generated by the aidl tool and the Stub subclass implementing the RPC methods. Clients of the service would have only the interface file generated by the aidl tool. Here's how a connection between a service and its clients is set up: Clients of the service (on the local side) would implement onServiceConnected() and onServiceDisconnected() methods so they can be notified when a successful connection to the remote service is established, and when it goes away. They would then call bindService() to set up the connection. The service's onBind() method would be implemented to either accept or reject the connection, depending on the intent it receives (the intent passed tobindService()). If the connection is accepted, it returns an instance of the Stub subclass. If the service accepts the connection, Android calls the client's onServiceConnected() method and passes it an IBinder object, a proxy for the Stub subclass managed by the service. Through the proxy, the client can make calls on the remote service. This brief description omits some details of the RPC mechanism. For more information, see Designing a Remote Interface Using AIDL and the IBinder class description. Thread-safe methods In a few contexts, the methods you implement may be called from more than one thread, and therefore must be written to be thread-safe. This is primarily true for methods that can be called remotely — as in the RPC mechanism discussed in the previous section. When a call on a method implemented in an IBinder object originates in the same process as the IBinder, the method is executed in the caller's thread. However, when the call originates in another process, the method is executed in a thread chosen from a pool of threads that Android maintains in the same process as the IBinder; it's not executed in the main thread of the process. For example, whereas a service's onBind() method would be called from the main thread of the service's process, methods implemented in the object thatonBind() returns (for example, a Stub subclass that implements RPC methods) would be called from threads in the pool. Since services can have more than one client, more than one pool thread can engage the same IBinder method at the same time. IBinder methods must, therefore, be implemented to be thread-safe.
  • 35. Android Mobile Application Development Mr. Pritesh N. Patel Page 35 Similarly, a content provider can receive data requests that originate in other processes. Although the ContentResolver and ContentProvider classes hide the details of how the interprocess communication is managed, ContentProvider methods that respond to those requests — the methods query(), insert(), delete(), update(), and getType() — are called from a pool of threads in the content provider's process, not the main thread of the process. Since these methods may be called from any number of threads at the same time, they too must be implemented to be thread-safe. Component Lifecycles Application components have a lifecycle — a beginning when Android instantiates them to respond to intents through to an end when the instances are destroyed. In between, they may sometimes be active or inactive,or, in the case of activities, visible to the user or invisible. This section discusses the lifecycles of activities, services, and broadcast receivers — including the states that they can be in during their lifetimes, the methods that notify you of transitions between states, and the effect of those states on the possibility that the process hosting them might be terminated and the instances destroyed. 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 alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations. It is stopped if it is completely obscured by another activity. It still retains all state and member information. However, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere. If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish() method), or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state. As an activity transitions from state to state, it is notified of the change by calls to the following protected methods: void onCreate(Bundle savedInstanceState) void onStart() void onRestart() void onResume()
  • 36. Android Mobile Application Development Mr. Pritesh N. Patel Page 36 void onPause() void onStop() void onDestroy() All of these methods are hooks that you can override to do appropriate work when the state changes. All activities must implement onCreate() to do the initial setup when the object is first instantiated. Many will also implement onPause() to commit data changes and otherwise prepare to stop interacting with the user. Calling into the superclass An implementation of any activity lifecycle method should always first call the superclass version. For example: protected void onPause() { super.onPause(); . . . } Taken together, these seven methods define the entire lifecycle of an activity. There are three nested loops that you can monitor by implementing them: The entire lifetime of an activity happens between the first call to onCreate() through to a single final call to onDestroy(). An activity does all its initial setup of "global" state in onCreate(), and releases all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread inonDestroy(). The visible lifetime of an activity happens between a call to onStart() until a corresponding call toonStop(). During this time, the user can see the activity on-screen, though it may not be in the foreground and interacting with the user. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver inonStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The onStart()and onStop() methods can be called multiple times, as the activity alternates between being visible and hidden to the user. The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time, the activity is in front of all other activities on screen and is interacting with the user. An activity can frequently transition between the resumed and paused states — for example, onPause() is called when the device goes to sleep or when a new activity is started, onResume() is called when an activity result
  • 37. Android Mobile Application Development Mr. Pritesh N. Patel Page 37 or a new intent is delivered. Therefore, the code in these two methods should be fairly lightweight. The following diagram illustrates these loops and the paths an activity may take between states. The colored ovals are major states the activity can be in. The square rectangles represent the callback methods you can implement to perform operations when the activity transitions between states. The following table describes each of these methods in more detail and locates it within the activity's overall lifecycle: Method Description Killable ? Next onCreate() Called when the activity is first created. This is where you should do all of your normal No onStart()
  • 38. Android Mobile Application Development Mr. Pritesh N. Patel Page 38 Method Description Killable ? Next static set up — create views, bind data to lists, and so on. This method is passed a Bundle object containing the activity's previous state, if that state was captured (see Saving Activity State, later). Always followed by onStart(). onRestart() Called after the activity has been stopped, just prior to it being started again. Always followed by onStart() No onStart() onStart() Called just before the activity becomes visible to the user. Followed by onResume() if the activity comes to the foreground, oronStop() if it becomes hidden. No onResume() or onStop() onResume() Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it. Always followed by onPause(). No onPause() onPause() Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does Yes onResume() or onStop()
  • 39. Android Mobile Application Development Mr. Pritesh N. Patel Page 39 Method Description Killable ? Next very quickly, because the next activity will not be resumed until it returns. Followed either by onResume() if the activity returns back to the front, or by onStop() if it becomes invisible to the user. onStop() Called when the activity is no longer visible to the user. This may happen because it is being destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it. Followed either by onRestart() if the activity is coming back to interact with the user, or by onDestroy() if this activity is going away. Yes onRestart() or onDestroy() onDestroy() Called before the activity is destroyed. This is the final call that the activity will receive. It could be called either because the activity is finishing (someone called finish() on it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method. Yes nothing Note the Killable column in the table above. It indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity's code. Three methods (onPause(), onStop(), and onDestroy()) are
  • 40. Android Mobile Application Development Mr. Pritesh N. Patel Page 40 marked "Yes." Because onPause() is the first of the three, it's the only one that's guaranteed to be called before the process is killed — onStop() and onDestroy() may not be. Therefore, you should use onPause() to write any persistent data (such as user edits) to storage. Methods that are marked "No" in the Killable column protect the process hosting the activity from being killed from the moment they are called. Thus an activity is in a killable state, for example, from the time onPause() returns to the time onResume() is called. It will not again be killable until onPause() again returns. As noted in a later section, Processes and lifecycle, an activity that's not technically "killable" by this definition might still be killed by the system — but that would happen only in extreme and dire circumstances when there is no other recourse. Saving activity state When the system, rather than the user, shuts down an activity to conserve memory, the user may expect to return to the activity and find it in its previous state. To capture that state before the activity is killed, you can implement an onSaveInstanceState() method for the activity. Android calls this method before making the activity vulnerable to being destroyed — that is, before onPause() is called. It passes the method a Bundle object where you can record the dynamic state of the activity as name- value pairs. When the activity is again started, the Bundle is passed both to onCreate() and to a method that's called after onStart(),onRestoreInstanceState(), so that either or both of them can recreate the captured state. Unlike onPause() and the other methods discussed earlier, onSaveInstanceState() and onRestoreInstanceState() are not lifecycle methods. They are not always called. For example, Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key). In that case, the user won't expect to return to the activity, so there's no reason to save its state. Because onSaveInstanceState() is not always called, you should use it only to record the transient state of the activity, not to store persistent data. UseonPause() for that purpose instead. Coordinating activities When one activity starts another, they both experience lifecycle transitions. One pauses and may stop, while the other starts up. On occasion, you may need to coordinate these activities, one with the other.
  • 41. Android Mobile Application Development Mr. Pritesh N. Patel Page 41 The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process: 1. The current activity's onPause() method is called. 2. Next, the starting activity's onCreate(), onStart(), and onResume() methods are called in sequence. 3. Then, if the starting activity is no longer visible on screen, its onStop() method is called. Service lifecycle A service can be used in two ways: It can be started and allowed to run until someone stops it or it stops itself. In this mode, it's started by calling Context.startService() and stopped by callingContext.stopService(). It can stop itself by calling Service.stopSelf() or Service.stopSelfResult(). Only one stopService() call is needed to stop the service, no matter how many times startService() was called. It can be operated programmatically using an interface that it defines and exports. Clients establish a connection to the Service object and use that connection to call into the service. The connection is established by calling Context.bindService(), and is closed by calling Context.unbindService(). Multiple clients can bind to the same service. If the service has not already been launched, bindService() can optionally launch it. The two modes are not entirely separate. You can bind to a service that was started with startService(). For example, a background music service could be started by calling startService() with an Intent object that identifies the music to play. Only later, possibly when the user wants to exercise some control over the player or get information about the current song, would an activity establish a connection to the service by calling bindService(). In cases like this, stopService() will not actually stop the service until the last binding is closed. Like an activity, a service has lifecycle methods that you can implement to monitor changes in its state. But they are fewer than the activity methods — only three — and they are public, not protected: void onCreate() void onStart(Intent intent) void onDestroy() By implementing these methods, you can monitor two nested loops of the service's lifecycle: The entire lifetime of a service happens between the time onCreate() is called and the time onDestroy() returns. Like an activity, a service does its initial setup in onCreate(), and releases all remaining resources in onDestroy(). For example, a music playback service
  • 42. Android Mobile Application Development Mr. Pritesh N. Patel Page 42 could create the thread where the music will be played in onCreate(), and then stop the thread in onDestroy(). The active lifetime of a service begins with a call to onStart(). This method is handed the Intent object that was passed to startService(). The music service would open the Intent to discover which music to play, and begin the playback. There's no equivalent callback for when the service stops — no onStop() method. The onCreate() and onDestroy() methods are called for all services, whether they're started by Context.startService() or Context.bindService(). However, onStart() is called only for services started by startService(). If a service permits others to bind to it, there are additional callback methods for it to implement: IBinder onBind(Intent intent) boolean onUnbind(Intent intent) void onRebind(Intent intent) The onBind() callback is passed the Intent object that was passed to bindService and onUnbind() is handed the intent that was passed to unbindService(). If the service permits the binding, onBind() returns the communications channel that clients use to interact with the service. The onUnbind() method can ask foronRebind() to be called if a new client connects to the service. The following diagram illustrates the callback methods for a service. Although, it separates services that are created via startService from those created bybindService(), keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it, so any service may receive onBind() andonUnbind() calls.
  • 43. Android Mobile Application Development Mr. Pritesh N. Patel Page 43 Broadcast receiver lifecycle A broadcast receiver has single callback method: void onReceive(Context curContext, Intent broadcastMsg) When a broadcast message arrives for the receiver, Android calls its onReceive() method and passes it the Intent object containing the message. The broadcast receiver is considered to be active only while it is executing this method. When onReceive() returns, it is inactive. A process with an active broadcast receiver is protected from being killed. But a process with only inactive components can be killed by the system at any time, when the memory it consumes is needed by other processes. This presents a problem when the response to a broadcast message is time consuming and, therefore, something that should be done in a separate thread, away from the main thread where other components of the user interface run. If onReceive() spawns the thread and then returns, the entire process, including the new thread, is judged to be inactive (unless other application components are active in the process), putting it in jeopardy of being killed. The solution to this problem is foronReceive() to start a service and let the service do the job, so the system knows that there is still active work being done in the process. The next section has more on the vulnerability of processes to being killed. Processes and lifecycles The Android system tries to maintain an application process for as long as possible, but eventually it will need to remove old processes when memory runs low. To determine which
  • 44. Android Mobile Application Development Mr. Pritesh N. Patel Page 44 processes to keep and which to kill, Android places each process into an "importance hierarchy" based on the components running in it and the state of those components. Processes with the lowest importance are eliminated first, then those with the next lowest, and so on. There are five levels in the hierarchy. The following list presents them in order of importance: 1. A foreground process is one that is required for what the user is currently doing. A process is considered to be in the foreground if any of the following conditions hold: o It is running an activity that the user is interacting with (the Activity object's onResume() method has been called). o It hosts a service that's bound to the activity that the user is interacting with. o It has a Service object that's executing one of its lifecycle callbacks (onCreate(), onStart(), or onDestroy()). o It has a BroadcastReceiver object that's executing its onReceive() method. Only a few foreground processes will exist at any given time. They are killed only as a last resort — if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a memory paging state, so killing some foreground processes is required to keep the user interface responsive. 2. A visible process is one that doesn't have any foreground components, but still can affect what the user sees on screen. A process is considered to be visible if either of the following conditions holds: o It hosts an activity that is not in the foreground, but is still visible to the user (its onPause() method has been called). This may occur, for example, if the foreground activity is a dialog that allows the previous activity to be seen behind it. o It hosts a service that's bound to a visible activity. A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running. 3. A service process is one that is running a service that has been started with the startService() method and that does not fall into either of the two higher categories. Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing an mp3 in the background or downloading data on the network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes. 4. A background process is one holding an activity that's not currently visible to the user (the Activity object's onStop() method has been called). These processes have no direct impact on the user experience, and can be killed at any time to reclaim memory for a foreground, visible, or service process. Usually there are many background processes running, so they
  • 45. Android Mobile Application Development Mr. Pritesh N. Patel Page 45 are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by the user is the last to be killed. If an activity implements its lifecycle methods correctly, and captures its current state, killing its process will not have a deleterious effect on the user experience. 5. An empty process is one that doesn't hold any active application components. The only reason to keep such a process around is as a cache to improve startup time the next time a component needs to run in it. The system often kills these processes in order to balance overall system resources between process caches and the underlying kernel caches. Android ranks a process at the highest level it can, based upon the importance of the components currently active in the process. For example, if a process hosts a service and a visible activity, the process will be ranked as a visible process, not a service process. In addition, a process's ranking may be increased because other processes are dependent on it. A process that is serving another process can never be ranked lower than the process it is serving. For example, if a content provider in process A is serving a client in process B, or if a service in process A is bound to a component in process B, process A will always be considered at least as important as process B. Because a process running a service is ranked higher than one with background activities, an activity that initiates a long-running operation might do well to start a service for that operation, rather than simply spawn a thread — particularly if the operation will likely outlast the activity. Examples of this are playing music in the background and uploading a picture taken by the camera to a web site. Using a service guarantees that the operation will have at least "service process" priority, regardless of what happens to the activity. As noted in the Broadcast receiver lifecycle section earlier, this is the same reason that broadcast receivers should employ services rather than simply put time-consuming operations in a thread. Application Resources You should always externalize resources such as images and strings from your application code, so that you can maintain them independently. Externalizing your resources also allows you to provide alternative resources that support specific device configurations such as different languages or screen sizes, which becomes increasingly important as more Android-powered devices become available with different configurations. In order to provide compatibility with different configurations, you must organize resources in your project's res/directory, using various sub-directories that group resources by type and configuration.
  • 46. Android Mobile Application Development Mr. Pritesh N. Patel Page 46 Figure 1. Two different devices, both using default resources. Figure 2. Two different devices, one using alternative resources. For any type of resource, you can specify default and multiple alternative resources for your application: Default resources are those that should be used regardless of the device configuration or when there are no alternative resources that match the current configuration. Alternative resources are those that you've designed for use with a specific configuration. To specify that a group of resources are for a specific configuration, append an appropriate configuration qualifier to the directory name. For example, while your default UI layout is saved in the res/layout/ directory, you might specify a different UI layout to be used when the screen is in landscape orientation, by saving it in the res/layout-land/ directory. Android automatically applies the appropriate resources by matching the device's current configuration to your resource directory names. Figure 1 demonstrates how a collection of default resources from an application are applied to two different devices when there are no alternative resources available. Figure 2 shows the same application with a set of alternative resources that qualify for one of the device configurations, thus, the two devices uses different resources. The information above is just an introduction to how application resources work on Android. The following documents provide a complete guide to how you can organize your application resources, specify alternative resources, access them in your application, and more:
  • 47. Android Mobile Application Development Mr. Pritesh N. Patel Page 47 Providing Resources What kinds of resources you can provide in your app, where to save them, and how to create alternative resources for specific device configurations. Accessing Resources How to use the resources you've provided, either by referencing them from your application code or from other XML resources. Handling Runtime Changes How to manage configuration changes that occur while your Activity is running. Localization A bottom-up guide to localizing your application using alternative resources. While this is just one specific use of alternative resources, it is very important in order to reach more users. Resource Types A reference of various resource types you can provide, describing their XML elements, attributes, and syntax. For example, this reference shows you how to create a resource for application menus, drawables, animations, and more. Resource Types Each of the documents in this section describe the usage, format and syntax for a certain type of application resource that you can provide in your resources directory (res/). Here's a brief summary of each resource type: Animation Resources Define pre-determined animations. Tween animations are saved in res/anim/ and accessed from the R.anim class. Frame animations are saved in res/drawable/ and accessed from the R.drawable class. Color State List Resource Define a color resources that changes based on the View state. Saved in res/color/ and accessed from the R.color class. Drawable Resources Define various graphics with bitmaps or XML. Saved in res/drawable/ and accessed from the R.drawable class. Layout Resource Define the layout for your application UI. Saved in res/layout/ and accessed from the R.layout class. Menu Resource Define the contents of your application menus. Saved in res/menu/ and accessed from the R.menu class. String Resources Define strings, string arrays, and plurals (and include string formatting and styling). Saved in res/values/ and accessed from the R.string, R.array, and R.plurals classes. Style Resource Define the look and format for UI elements. Saved in res/values/ and accessed from the R.style class. More Resource Types
  • 48. Android Mobile Application Development Mr. Pritesh N. Patel Page 48 Define values such as booleans, integers, dimensions, colors, and other arrays. Saved in res/values/ but each accessed from unique R sub-classes (such as R.bool, R.integer, R.dimen, etc.). Applying Styles and Themes A style is a collection of properties that specify the look and format for a View or window. A style can specify properties such as height, padding, font color, font size, background color, and much more. A style is defined in an XML resource that is separate from the XML that specifies the layout. Styles in Android share a similar philosophy to cascading stylesheets in web design—they allow you to separate the design from the content. For example, by using a style, you can take this layout XML: <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#00FF00" android:typeface="monospace" android:text="@string/hello" /> And turn it into this: <TextView style="@style/CodeFont" android:text="@string/hello" /> All of the attributes related to style have been removed from the layout XML and put into a style definition called CodeFont, which is then applied with the styleattribute. You'll see the definition for this style in the following section. A theme is a style applied to an entire Activity or application, rather than an individual View (as in the example above). When a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CodeFont style as a theme for an Activity and then all text inside that Activity will have green monospace font. Defining Styles
  • 49. Android Mobile Application Development Mr. Pritesh N. Patel Page 49 To create a set of styles, save an XML file in the res/values/ directory of your project. The name of the XML file is arbitrary, but it must use the .xml extension and be saved in the res/values/ folder. The root node of the XML file must be <resources>. For each style you want to create, add a <style> element to the file with a name that uniquely identifies the style (this attribute is required). Then add an <item>element for each property of that style, with a name that declares the style property and a value to go with it (this attribute is required). The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property. Here's an example file with a single style: <?xml version="1.0" encoding="utf-8"?> <resources> <style name="CodeFont" parent="@android:style/TextAppearance.Medium"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textColor">#00FF00</item> <item name="android:typeface">monospace</item> </style> </resources> Each child of the <resources> element is converted into an application resource object at compile-time, which can be referenced by the value in the <style> element'sname attribute. This example style can be referenced from an XML layout as @style/CodeFont (as demonstrated in the introduction above). The parent attribute in the <style> element is optional and specifies the resource ID of another style from which this style should inherit properties. You can then override the inherited style properties if you want to. Remember, a style that you want to use as an Activity or application theme is defined in XML exactly the same as a style for a View. A style such as the one defined above can be applied as a style for a single View or as a theme for an entire Activity or application. How to apply a style for a single View or as an application theme is discussed later. Inheritance The parent attribute in the <style> element lets you specify a style from which your style should inherit properties. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add. You can inherit from styles that you've created yourself or from styles that are built into the platform. (See Using
  • 50. Android Mobile Application Development Mr. Pritesh N. Patel Page 50 Platform Styles and Themes, below, for information about inheriting from styles defined by the Android platform.) For example, you can inherit the Android platform's default text appearance and then modify it: <style name="GreenText" parent="@android:style/TextAppearance"> <item name="android:textColor">#00FF00</item> </style> If you want to inherit from styles that you've defined yourself, you do not have to use the parent attribute. Instead, just prefix the name of the style you want to inherit to the name of your new style, separated by a period. For example, to create a new style that inherits the CodeFont style defined above, but make the color red, you can author the new style like this: <style name="CodeFont.Red"> <item name="android:textColor">#FF0000</item> </style> Notice that there is no parent attribute in the <style> tag, but because the name attribute begins with the CodeFont style name (which is a style that you have created), this style inherits all style properties from that style. This style then overrides the android:textColor property to make the text red. You can reference this new style as @style/CodeFont.Red. You can continue inheriting like this as many times as you'd like, by chaining names with periods. For example, you can extend CodeFont.Red to be bigger, with: <style name="CodeFont.Red.Big"> <item name="android:textSize">30sp</item> </style> This inherits from both CodeFont and CodeFont.Red styles, then adds the android:textSize property. Note: This technique for inheritance by chaining together names only works for styles defined by your own resources. You can't inherit Android built-in styles this way. To reference a built-in style, such as TextAppearance, you must use the parent attribute. Style Properties Now that you understand how a style is defined, you need to learn what kind of style properties—defined by the <item> element—are available. You're probably familiar with
  • 51. Android Mobile Application Development Mr. Pritesh N. Patel Page 51 some already, such as layout_width and textColor. Of course, there are many more style properties you can use. The best place to find properties that apply to a specific View is the corresponding class reference, which lists all of the supported XML attributes. For example, all of the attributes listed in the table of TextView XML attributes can be used in a style definition for a TextView element (or one of its subclasses). One of the attributes listed in the reference is android:inputType, so where you might normally place the android:inputType attribute in an <EditText> element, like this: <EditText android:inputType="number" ... /> You can instead create a style for the EditText element that includes this property: <style name="Numbers"> <item name="android:inputType">number</item> ... </style> So your XML for the layout can now implement this style: <EditText style="@style/Numbers" ... /> This simple example may look like more work, but when you add more style properties and factor-in the ability to re-use the style in various places, the pay-off can be huge. For a reference of all available style properties, see the R.attr reference. Keep in mind that all View objects don't accept all the same style attributes, so you should normally refer to the specific View class for supported style properties. However, if you apply a style to a View that does not support all of the style properties, the View will apply only those properties that are supported and simply ignore the others. Some style properties, however, are not supported by any View element and can only be applied as a theme. These style properties apply to the entire window and not to any type of View. For example, style properties for a theme can hide the application title, hide the status bar, or change the window's background. These kind of style properties do not belong to any View object. To discover these theme-only style properties, look at
  • 52. Android Mobile Application Development Mr. Pritesh N. Patel Page 52 the R.attr reference for attributes that begin with window. For instance, windowNoTitle and windowBackground are style properties that are effective only when the style is applied as a theme to an Activity or application. See the next section for information about applying a style as a theme. Note: Don't forget to prefix the property names in each <item> element with the android: namespace. For example: <item name="android:inputType">. Applying Styles and Themes to the UI There are two ways to set a style: To an individual View, by adding the style attribute to a View element in the XML for your layout. Or, to an entire Activity or application, by adding the android:theme attribute to the <activity> or <application> element in the Android manifest. When you apply a style to a single View in the layout, the properties defined by the style are applied only to that View. If a style is applied to a ViewGroup, the childView elements will not inherit the style properties—only the element to which you directly apply the style will apply its properties. However, you can apply a style so that it applies to all View elements—by applying the style as a theme. To apply a style definition as a theme, you must apply the style to an Activity or application in the Android manifest. When you do so, every View within the Activity or application will apply each property that it supports. For example, if you apply the CodeFont style from the previous examples to an Activity, then all View elements that support the text style properties will apply them. Any View that does not support the properties will ignore them. If a View supports only some of the properties, then it will apply only those properties. Apply a style to a View Here's how to set a style for a View in the XML layout: <TextView style="@style/CodeFont" android:text="@string/hello" /> Now this TextView will be styled as defined by the style named CodeFont. (See the sample above, in Defining Styles.) Note: The style attribute does not use the android: namespace prefix.
  • 53. Android Mobile Application Development Mr. Pritesh N. Patel Page 53 Apply a theme to an Activity or application To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the <application> tag to include the android:theme attribute with the style name. For example: <application android:theme="@style/CustomTheme"> If you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag instead. Just as Android provides other built-in resources, there are many pre-defined themes that you can use, to avoid writing them yourself. For example, you can use theDialog theme and make your Activity appear like a dialog box: <activity android:theme="@android:style/Theme.Dialog"> Or if you want the background to be transparent, use the Translucent theme: <activity android:theme="@android:style/Theme.Translucent"> If you like a theme, but want to tweak it, just add the theme as the parent of your custom theme. For example, you can modify the traditional dialog theme to use your own background image like this: <style name="CustomDialogTheme" parent="@android:style/Theme.Dialog"> <item name="android:windowBackground">@drawable/custom_dialog_background</item> </style> Now use CustomDialogTheme instead of Theme.Dialog inside the Android Manifest: <activity android:theme="@style/CustomDialogTheme"> Using Platform Styles and Themes The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.styleclass. To use
  • 54. Android Mobile Application Development Mr. Pritesh N. Patel Page 54 the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with"@android:style/Theme.NoTitleBar". The R.style reference, however, is not well documented and does not thoroughly describe the styles, so viewing the actual source code for these styles and themes will give you a better understanding of what style properties each one provides. For a better reference to the Android styles and themes, see the following source code: Android Styles (styles.xml) Android Themes (themes.xml) These files will help you learn through example. For instance, in the Android themes source code, you'll find a declaration for <style name="Theme.Dialog">. In this definition, you'll see all of the properties that are used to style dialogs that are used by the Android framework. For more information about the syntax used to create styles in XML, see Available Resource Types: Style and Themes. For a reference of available style attributes that you can use to define a style or theme (e.g., "windowBackground" or "textAppearance"), see R.attr or the respective View class for which you are creating a style. Using the Dalvik Debug Monitor Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more. This page provides a modest discussion of DDMS features; it is not an exhaustive exploration of all the features and capabilities. DDMS ships in the tools/ directory of the SDK. Enter this directory from a terminal/console and type ddms (or ./ddms on Mac/Linux) to run it. DDMS will work with both the emulator and a connected device. If both are connected and running simultaneously, DDMS defaults to the emulator. How DDMS works DDMS acts as a middleman to connect the IDE to the applications running on the device. On Android, every application runs in its own process, each of which hosts its own virtual machine (VM). And each process listens for a debugger on a different port. When it starts, DDMS connects to adb and starts a device monitoring service between the two, which will notify DDMS when a device is connected or disconnected. When a device is connected, a VM monitoring service is created between adb and DDMS, which will notify DDMS when a VM on the device is started or terminated. Once a VM is running, DDMS
  • 55. Android Mobile Application Development Mr. Pritesh N. Patel Page 55 retrieves the the VM's process ID (pid), via adb, and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a custom wire protocol. For each VM on the device, DDMS opens a port upon which it will listen for a debugger. For the first VM, DDMS listens for a debugger on port 8600, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwarded between the debugger and the associated VM. Debugging can then process like any remote debugging session. DDMS also opens another local port, the DDMS "base port" (8700, by default), upon which it also listens for a debugger. When a debugger connects to this base port, all traffic is forwarded to the VM currently selected in DDMS, so this is typically where you debugger should connect. For more information on port-forwarding with DDMS, read Configuring your IDE to attach to port 8700 for debugging. Tip: You can set a number of DDMS preferences in File > Preferences. Preferences are saved to "$HOME/.ddmsrc". Known debugging issues with Dalvik Debugging an application in the Dalvik VM should work the same as it does in other VMs. However, when single-stepping out of synchronized code, the "current line" cursor may jump to the last line in the method for one step. Left Pane The left side of the Debug Monitor shows each emulator/device currently found, with a list of all the VMs currently running within each. VMs are identified by the package name of the application it hosts. Use this list to find and attach to the VM running the activity(ies) that you want to debug. Next to each VM in the list is a "debugger pass-through" port (in the right-most column). If you connect your debugger to one of the the ports listed, you will be connected to the corresponding VM on the device. However, when using DDMS, you need only connect to port 8700, as DDMS forwards all traffic here to the currently selected VM. (Notice, as you select a VM in the list, the listed port includes 8700.) This way, there's no need to reconfigure the debugger's port each time you switch between VMs. When an application running on the device calls waitForDebugger() (or you select this option in the developer options), a red icon will be shown next to the client name, while it waits for the debugger to attach to the VM. When a debugger is connected, the icon will turn green.
  • 56. Android Mobile Application Development Mr. Pritesh N. Patel Page 56 If you see a crossed-out bug icon, this means that the DDMS was unable to complete a connection between the debugger and the VM because it was unable to open the VM's local port. If you see this for all VMs on the device, it is likely because you have another instance of DDMS running (this includes the Eclipse plugin). If you see a question mark in place of an application package, this means that, once DDMS received the application pid from adb, it somehow failed to make a successful handshake with the VM process. Try restarting DDMS. Right pane On the right side, the Debug Monitor provides tabs that display useful information and some pretty cool tools. Info This view shows some general information about the selected VM, including the process ID, package name, and VM version. Threads The threads view has a list of threads running in the process of the target VM. To reduce the amount of data sent over the wire, the thread updates are only sent when explicitly enabled by toggling the "threads" button in the toolbar. This toggle is maintained per VM. This tab includes the following information: ID - a VM-assigned unique thread ID. In Dalvik, these are odd numbers starting from 3. Tid - the Linux thread ID. For the main thread in a process, this will match the process ID. Status - the VM thread status. Daemon threads are shown with an asterisk (*). This will be one of the following: o running - executing application code o sleeping - called Thread.sleep() o monitor - waiting to acquire a monitor lock o wait - in Object.wait() o native - executing native code o vmwait - waiting on a VM resource o zombie - thread is in the process of dying o init - thread is initializing (you shouldn't see this) o starting - thread is about to start (you shouldn't see this either) utime - cumulative time spent executing user code, in "jiffies" (usually 10ms). stime - cumulative time spent executing system code, in "jiffies" (usually 10ms). Name - the name of the thread "ID" and "Name" are set when the thread is started. The remaining fields are updated periodically (default is every 4 seconds).
  • 57. Android Mobile Application Development Mr. Pritesh N. Patel Page 57 VM Heap Displays some heap stats, updated during garbage collection. If, when a VM is selected, the VM Heap view says that heap updates are not enabled, click the "Show heap updates" button, located in the top-left toolbar. Back in the VM Heap view, click Cause GC to perform garbage collection and update the heap stats. Allocation Tracker In this view, you can track the memory allocation of each virtual machine. With a VM selected in the left pane, click Start Tracking, then Get Allocations to view all allocations since tracking started. The table below will be filled with all the relevant data. Click it again to refresh the list. Emulator Control With these controls, you can simulate special device states and activities. Features include: Telephony Status - change the state of the phone's Voice and Data plans (home, roaming, searching, etc.), and simulate different kinds of network Speed and Latency (GPRS, EDGE, UTMS, etc.). Telephony Actions - perform simulated phone calls and SMS messages to the emulator. Location Controls - send mock location data to the emulator so that you can perform location-aware operations like GPS mapping. To use the Location Controls, launch your application in the Android emulator and open DDMS. Click the Emulator Controls tab and scroll down to Location Controls. From here, you can: o Manually send individual longitude/latitude coordinates to the device. Click Manual, select the coordinate format, fill in the fields and click Send. o Use a GPX file describing a route for playback to the device. Click GPX and load the file. Once loaded, click the play button to playback the route for your location-aware application. When performing playback from GPX, you can adjust the speed of playback from the DDMS panel and control playback with the pause and skip buttons. DDMS will parse both the waypoints (<wpt>, in the first table), and the tracks (<trk>, in the second table, with support for multiple segments, <trkseg>, although they are simply concatenated). Only the tracks can be played. Clicking a waypoint in the first list simply sends its coordinate to the device, while selecting a track lets you play it. o Use a KML file describing individual placemarks for sequenced playback to the device. Click KML and load the file. Once loaded, click the play button to send the coordinates to your location-aware application.
  • 58. Android Mobile Application Development Mr. Pritesh N. Patel Page 58 When using a KML file, it is parsed for a <coordinates> element. The value of which should be a single set of longitude, latitude and altitude figures. For example: <coordinates>-122.084143,37.421972,4</coordinates> In your file, you may include multiple <Placemark> elements, each containing a <coordinates> element. When you do so, the collection of placemarks will be added as tracks. DDMS will send one placemark per second to the device. One way to generate a suitable KML file is to find a location in Google Earth. Right-click the location entry that appears on the left and select "Save place as..." with the save format set to Kml. Note: DDMS does not support routes created with the <MultiGeometry><LineString>lat1, long1, lat2, long2, ....</LineString></MultiGeometry> methods. There is also currently no support for the <TimeStamp> node inside the <Placemark>. Future releases may support timed placement and routes within a single coordinate element. File Explorer With the File Explorer, you can view the device file system and perform basic management, like pushing and pulling files. This circumvents using the adb push and pullcommands, with a GUI experience. With DDMS open, select Device > File Explorer... to open the File Explorer window. You can drag-and-drop into the device directories, but cannot drag out of them. To copy files from the device, select the file and click the Pull File from Device button in the toolbar. To delete files, use the Delete button in the toolbar. If you're interested in using an SD card image on the emulator, you're still required to use the mksdcard command to create an image, and then mount it during emulator bootup. For example, from the /tools directory, execute: $ mksdcard 1024M ./img $ emulator -sdcard ./img Now, when the emulator is running, the DDMS File Explorer will be able to read and write to the sdcard directory. However, your files may not appear automatically. For example, if you add an MP3 file to the sdcard, the media player won't see them until you restart the emulator. (When restarting the emulator from command line, be sure to mount the sdcard again.) Screen Capture
  • 59. Android Mobile Application Development Mr. Pritesh N. Patel Page 59 You can capture screen images on the device or emulator by selecting Device > Screen capture... in the menu bar, or press CTRL-S. Be sure to select a device first. Exploring Processes You can see the output of ps -x for a specific VM by selecting Device > Show process status... in the menu bar. Cause a GC to Occur Cause garbage collection to occur in the selected application by pressing the trash can button on the toolbar. Running Dumpsys and Dumpstate on the Device (logcat) To run dumpsys (logcat) from Dalvik, select Device > Run logcat... in the menu bar. To run dumpstate from Dalvik, select Device > Dump device state... in the menu bar. Examine Radio State By default, radio state is not output during a standard logcat (it is a lot of information). To see radio information, either click Device > Dump radio state... or run logcat as described in Logging Radio Information. Stop a Virtual Machine You can stop a virtual machine by selecting Actions > Halt VM. Pressing this button causes the VM to call Runtime.halt(1). Traceview: A Graphical Log Viewer Traceview is a graphical viewer for execution logs saved by your application. Traceview can help you debug your application and profile its performance. The sections below describe how to use the program. Creating Trace Files To use Traceview, you need to generate log files containing the trace information you want to analyze. To do that, you include the Debug class in your code and call its methods to start and stop logging of trace information to disk. When your application quits, you can then use Traceview to examine the log files for useful run-time information such as method calls and run times.
  • 60. Android Mobile Application Development Mr. Pritesh N. Patel Page 60 To create the trace files, include the Debug class and call one of the startMethodTracing() methods. In the call, you specify a base name for the trace files that the system generates. To stop tracing, call stopMethodTracing(). These methods start and stop method tracing across the entire virtual machine. For example, you could call startMethodTracing() in your activity's onCreate() method, and call stopMethodTracing() in that activity's onDestroy() method. // start tracing to "/sdcard/calc.trace" Debug.startMethodTracing("calc"); // ... // stop tracing Debug.stopMethodTracing(); When your application calls startMethodTracing(), the system creates a file called <trace- base-name>.trace. This contains the binary method trace data and a mapping table with thread and method names. The system then begins buffering the generated trace data, until your application calls stopMethodTracing(), at which time it writes the buffered data to the output file. If the system reaches the maximum buffer size before stopMethodTracing() is called, the system stops tracing and sends a notification to the console. Interpreted code will run more slowly when profiling is enabled. Don't try to generate absolute timings from the profiler results (i.e. "function X takes 2.5 seconds to run"). The times are only useful in relation to other profile output, so you can see if changes have made the code faster or slower. When using the Android emulator, you must create an SD card image upon which the trace files will be written. For example, from the /tools directory, you can create an SD card image named "imgcd" and mount it when launching the emulator like so: $ mksdcard 1024M ./imgcd $ emulator -sdcard ./imgcd Copying Trace Files to a Host Machine After your application has run and the system has created your trace files <trace-base- name>.trace on a device or emulator, you must copy those files to your development computer. You can use adb pull to copy the files. Here's an example that shows how to
  • 61. Android Mobile Application Development Mr. Pritesh N. Patel Page 61 copy an example file, calc.trace, from the default location on the emulator to the /tmp directory on the emulator host machine: adb pull /sdcard/calc.trace /tmp Viewing Trace Files in Traceview To run traceview and view the trace files, enter traceview <trace-base-name>. For example, to run Traceview on the example files copied in the previous section, you would use: traceview /tmp/calc Traceview loads the log files and displays their data in a window that has two panels: A timeline panel -- describes when each thread and method started and stopped A profile panel -- provides a summary of what happened inside a method The sections below provide addition information about the traceview output panes. Timeline Panel The image below shows a close up of the timeline panel. Each thread’s execution is shown in its own row, with time increasing to the right. Each method is shown in another color (colors are reused in a round-robin fashion starting with the methods that have the most inclusive time). The thin lines underneath the first row show the extent (entry to exit) of all the calls to the selected method. The method in this case is LoadListener.nativeFinished() and it was selected in the profile view.
  • 62. Android Mobile Application Development Mr. Pritesh N. Patel Page 62 Profile Panel The image below shows the profile pane. The profile pane shows a summary of all the time spent in a method. The table shows both the inclusive and exclusive times (as well as the percentage of the total time). Exclusive time is the time spent in the method. Inclusive time is the time spent in the method plus the time spent in any called functions. We refer to calling methods as "parents" and called methods as "children." When a method is selected (by clicking on it), it expands to show the parents and children. Parents are shown with a purple background and children with a yellow background. The last column in the table shows the number of calls to this method plus the number of recursive calls. The last column shows the number of calls out of the total number of calls made to that method. In this view, we can see that there were 14 calls to LoadListener.nativeFinished(); looking at the timeline panel shows that one of those calls took an unusually long time. Traceview File Format Tracing creates two distinct pieces of output: a data file, which holds the trace data, and a key file, which provides a mapping from binary identifiers to thread and method names. The files are concatenated when tracing completes, into a single .trace file. Note: The previous version of Traceview did not concatenate these files for you. If you have old key and data files that you'd still like to trace, you can concatenate them yourself with cat mytrace.key mytrace.data > mytrace.trace.
  • 63. Android Mobile Application Development Mr. Pritesh N. Patel Page 63 Data File Format The data file is binary, structured as follows (all values are stored in little-endian order): * File format: * header * record 0 * record 1 * ... * * Header format: * u4 magic 0x574f4c53 ('SLOW') * u2 version * u2 offset to data * u8 start date/time in usec * * Record format: * u1 thread ID * u4 method ID | method action * u4 time delta since start, in usec The application is expected to parse all of the header fields, then seek to "offset to data" from the start of the file. From there it just reads 9-byte records until EOF is reached. u8 start date/time in usec is the output from gettimeofday(). It's mainly there so that you can tell if the output was generated yesterday or three months ago. method action sits in the two least-significant bits of the method word. The currently defined meanings are: 0 - method entry 1 - method exit 2 - method "exited" when unrolled by exception handling 3 - (reserved) An unsigned 32-bit integer can hold about 70 minutes of time in microseconds. Key File Format The key file is a plain text file divided into three sections. Each section starts with a keyword that begins with '*'. If you see a '*' at the start of a line, you have found the start of a new section. An example file might look like this:
  • 64. Android Mobile Application Development Mr. Pritesh N. Patel Page 64 *version 1 clock=global *threads 1 main 6 JDWP Handler 5 Async GC 4 Reference Handler 3 Finalizer 2 Signal Handler *methods 0x080f23f8 java/io/PrintStream write ([BII)V 0x080f25d4 java/io/PrintStream print (Ljava/lang/String;)V 0x080f27f4 java/io/PrintStream println (Ljava/lang/String;)V 0x080da620 java/lang/RuntimeException <init> ()V [...] 0x080f630c android/os/Debug startMethodTracing ()V 0x080f6350 android/os/Debug startMethodTracing (Ljava/lang/String;Ljava/lang/String;I)V *end version section The first line is the file version number, currently 1. The second line, clock=global, indicates that we use a common clock across all threads. A future version may use per-thread CPU time counters that are independent for every thread. threads section One line per thread. Each line consists of two parts: the thread ID, followed by a tab, followed by the thread name. There are few restrictions on what a valid thread name is, so include everything to the end of the line. methods section One line per method entry or exit. A line consists of four pieces, separated by tab marks: method-ID [TAB] class-name [TAB] method-name [TAB] signature . Only the methods that were actually entered or exited are included in the list. Note that all three identifiers are required to uniquely identify a method. Traceview Known Issues Threads Traceview logging does not handle threads well, resulting in these two problems: 1. If a thread exits during profiling, the thread name is not emitted; 2. The VM reuses thread IDs. If a thread stops and another starts, they may get the same ID.
  • 65. Android Mobile Application Development Mr. Pritesh N. Patel Page 65 Using dmtracedump The Android SDK includes dmtracedump, a tool that gives you an alternate way of generating graphical call-stack diagrams from trace log files. The tool uses the Graphviz Dot utility to create the graphical output, so you need to install Graphviz before running dmtracedump. The dmtracedump tool generates the call stack data as a tree diagram, with each call represented as a node. It shows call flow (from parent node to child nodes) using arrows. The diagram below shows an example of dmtracedump output. For each node, dmtracedump shows <ref> callname (<inc-ms>, <exc-ms>,<numcalls>), where <ref> -- Call reference number, as used in trace logs <inc-ms> -- Inclusive elapsed time (milliseconds spent in method, including all child methods) <exc-ms> -- Exclusive elapsed time (milliseconds spent in method, not including any child methods) <numcalls> -- Number of calls The usage for dmtracedump is:
  • 66. Android Mobile Application Development Mr. Pritesh N. Patel Page 66 dmtracedump [-ho] [-s sortable] [-d trace-base-name] [-g outfile] <trace-base-name> The tool then loads trace log data from <trace-base-name>.data and <trace-base- name>.key. The table below lists the options for dmtracedump. Option Description -d <trace- base-name> Diff with this trace name -g <outfile> Generate output to <outfile> -h Turn on HTML output -o Dump the trace file instead of profiling -d <trace- base-name> URL base to the location of the sortable javascript file -t <percent> Minimum threshold for including child nodes in the graph (child's inclusive time as a percentage of parent inclusive time). If this option is not used, the default threshold is 20%. Tools Overview The Android SDK includes a variety of custom tools that help you develop mobile applications on the Android platform. The most important of these are the Android Emulator and the Android Development Tools plugin for Eclipse, but the SDK also includes a variety of other tools for debugging, packaging, and installing your applications on the emulator. Android Development Tools Plugin (for the Eclipse IDE) The ADT plugin adds powerful extensions to the Eclipse integrated environment, making creating and debugging your Android applications easier and faster. If you use Eclipse, the ADT plugin gives you an incredible boost in developing Android applications. Android Emulator
  • 67. Android Mobile Application Development Mr. Pritesh N. Patel Page 67 A QEMU-based device-emulation tool that you can use to design, debug, and test your applications in an actual Android run-time environment. Android Virtual Devices (AVDs) Virtual device configurations that you create, to model device characteristics in the Android Emulator. In each configuration, you can specify the Android platform to run, the hardware options, and the emulator skin to use. Each AVD functions as an independent device with it's own storage for user data, SD card, and so on. Hierarchy Viewer The Hierarchy Viewer tool allows you to debug and optimize your user interface. It provides a visual representation of your layout's hierarchy of Views and a magnified inspector of the current display with a pixel grid, so you can get your layout just right. layoutopt This tool lets you quickly analyze your application's layouts for efficiency. Draw 9-patch The Draw 9-patch tool allows you to easily create a NinePatch graphic using a WYSIWYG editor. It also previews stretched versions of the image, and highlights the area in which content is allowed. Dalvik Debug Monitor Service (ddms) Integrated with Dalvik, the Android platform's custom VM, this tool lets you manage processes on an emulator or device and assists in debugging. You can use it to kill processes, select a specific process to debug, generate trace data, view heap and thread information, take screenshots of the emulator or device, and more. Android Debug Bridge (adb) The adb tool lets you install your application's .apk files on an emulator or device and access the emulator or device from a command line. You can also use it to link a standard debugger to application code running on an Android emulator or device. Android Asset Packaging Tool (aapt) The aapt tool lets you create .apk files containing the binaries and resources of Android applications. Android Interface Description Language (aidl) Lets you generate code for an interprocess interface, such as what a service might use. sqlite3 Included as a convenience, this tool lets you access the SQLite data files created and used by Android applications. Traceview This tool produces graphical analysis views of trace log data that you can generate from your Android application. mksdcard Helps you create a disk image that you can use with the emulator, to simulate the presence of an external storage card (such as an SD card). dx The dx tool rewrites .class bytecode into Android bytecode (stored in .dex files.) UI/Application Exerciser Monkey
  • 68. Android Mobile Application Development Mr. Pritesh N. Patel Page 68 The Monkey is a program that runs on your emulator or device and generates pseudo-random streams of user events such as clicks, touches, or gestures, as well as a number of system- level events. You can use the Monkey to stress-test applications that you are developing, in a random yet repeatable manner. android A script that lets you manage AVDs and generate Ant build files that you can use to compile your Android applications. zipalign An important .apk optimization tool. This tool ensures that all uncompressed data starts with a particular alignment relative to the start of the file. This should always be used to align .apk files after they have been signed. Data Storage Your data storage options are the following: Shared Preferences Store private primitive data in key-value pairs. Internal Storage Store private data on the device memory. External Storage Store public data on the shared external storage. SQLite Databases Store structured data in a private database. Network Connection Store data on the web with your own network server. Android provides a way for you to expose even your private data to other applications — with a content provider. A content provider is an optional component that exposes read/write access to your application data, subject to whatever restrictions you want to impose. For more information about using content providers, see the Content Providers documentation. Using Shared Preferences The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can useSharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed). User Preferences Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, seePreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences). To get a SharedPreferences object for your application, use one of two methods:
  • 69. Android Mobile Application Development Mr. Pritesh N. Patel Page 69 getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter. getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name. To write values: 1. Call edit() to get a SharedPreferences.Editor. 2. Add values with methods such as putBoolean() and putString(). 3. Commit the new values with commit() To read values, use SharedPreferences methods such as getBoolean() and getString(). Here is an example that saves a preference for silent keypress mode in a calculator: public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); } @Override protected void onStop(){ super.onStop(); // We need an Editor object to make preference changes. // All objects are from android.context.Context SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean("silentMode", mSilentMode); // Commit the edits! editor.commit(); } }
  • 70. Android Mobile Application Development Mr. Pritesh N. Patel Page 70 Using the Internal Storage You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed. To create and write a private file to the internal storage: 1. Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream. 2. Write to the file with write(). 3. Close the stream with close(). For example: String FILENAME = "hello_file"; String string = "hello world!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close(); MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. Other modes available are: MODE_APPEND,MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE. To read a file from internal storage: 1. Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. 2. Read bytes from the file with read(). 3. Then close the stream with close(). Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it withopenRawResource(), passing the R.raw.<filename> resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file). Saving cache files If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.
  • 71. Android Mobile Application Development Mr. Pritesh N. Patel Page 71 When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed. Other useful methods getFilesDir() Gets the absolute path to the filesystem directory where your internal files are saved. getDir() Creates (or opens an existing) directory within your internal storage space. deleteFile() Deletes a file saved on the internal storage. fileList() Returns an array of files currently saved by your application. Using the External Storage Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non- removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer. Caution: External files can disappear if the user mounts the external storage on a computer or removes the media, and there's no security enforced upon files you save to the external storage. All applications can read and write files placed on the external storage and the user can remove them. Checking media availability Before you do any work with the external storage, you should always call getExternalStorageState() to check whether the media is available. The media might be mounted to a computer, missing, read-only, or in some other state. For example, here's how you can check the availability: boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false;
  • 72. Android Mobile Application Development Mr. Pritesh N. Patel Page 72 } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } This example checks whether the external storage is available to read and write. The getExternalStorageState() method returns other states that you might want to check, such as whether the media is being shared (connected to a computer), is missing entirely, has been removed badly, etc. You can use these to notify the user with more information when your application needs to access the media. Accessing files on external storage If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory). This method will create the appropriate directory if necessary. By specifying the type of directory, you ensure that the Android's media scanner will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music). If the user uninstalls your application, this directory and all its contents will be deleted. If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory: /Android/data/<package_name>/files/ The <package_name> is your Java-style package name, such as "com.example.android.app". If the user's device is running API Level 8 or greater and they uninstall your application, this directory and all its contents will be deleted. Hiding your files from the Media Scanner Include an empty file named .nomedia in your external files directory (note the dot prefix in the filename). This will prevent Android's media scanner from reading your media files and including them in apps like Gallery or Music. Saving files that should be shared If you want to save files that are not specific to your application and that should not be deleted when your application is uninstalled, save them to one of the public directories on the external storage. These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and others.
  • 73. Android Mobile Application Development Mr. Pritesh N. Patel Page 73 In API Level 8 or greater, use getExternalStoragePublicDirectory(), passing it the type of public directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others. This method will create the appropriate directory if necessary. If you're using API Level 7 or lower, use getExternalStorageDirectory() to open a File that represents the root of the external storage, then save your shared files in one of the following directories: Music/ - Media scanner classifies all media found here as user music. Podcasts/ - Media scanner classifies all media found here as a podcast. Ringtones/ - Media scanner classifies all media found here as a ringtone. Alarms/ - Media scanner classifies all media found here as an alarm sound. Notifications/ - Media scanner classifies all media found here as a notification sound. Pictures/ - All photos (excluding those taken with the camera). Movies/ - All movies (excluding those taken with the camcorder). Download/ - Miscellaneous downloads. Saving cache files If you're using API Level 8 or greater, use getExternalCacheDir() to open a File that represents the external storage directory where you should save cache files. If the user uninstalls your application, these files will be automatically deleted. However, during the life of your application, you should manage these cache files and remove those that aren't needed in order to preserve file space. If you're using API Level 7 or lower, use getExternalStorageDirectory() to open a File that represents the root of the external storage, then write your cache data in the following directory: /Android/data/<package_name>/cache/ The <package_name> is your Java-style package name, such as "com.example.android.app". Using Databases Android provides full support for SQLite databases. Any databases you create will be accessible by name to any class in the application, but not outside the application. The recommended method to create a new SQLite database is to create a subclass of SQLiteOpenHelper and override the onCreate() method, in which you can execute a SQLite command to create tables in the database. For example:
  • 74. Android Mobile Application Development Mr. Pritesh N. Patel Page 74 public class DictionaryOpenHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 2; private static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final String DICTIONARY_TABLE_CREATE = "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" + KEY_WORD + " TEXT, " + KEY_DEFINITION + " TEXT);"; DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DICTIONARY_TABLE_CREATE); } } You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've defined. To write to and read from the database, callgetWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations. Android does not impose any limitations beyond the standard SQLite concepts. We do recommend including an autoincrement value key field that can be used as a unique ID to quickly find a record. This is not required for private data, but if you implement a content provider, you must include a unique ID using the BaseColumns._ID constant. You can execute SQLite queries using the SQLiteDatabase query() methods, which accept various query parameters, such as the table to query, the projection, selection, columns, grouping, and others. For complex queries, such as those that require column aliases, you should use SQLiteQueryBuilder, which provides several convienent methods for building queries. Every SQLite query will return a Cursor that points to all the rows found by the query. The Cursor is always the mechanism with which you can navigate results from a database query and read rows and columns.