ANDROID APPLICATION DEVELOPMENT<br />Ramesh Prasad<br />
INTRODUCTION<br />
Android Devices<br />
Mobile Operating System ?<br />
A BRIEF HISTORY OF ANDROID<br />
History<br />Android, Inc. was founded in Palo Alto, California, United States in October, 2003 by Andy Rubin and others<b...
Licensing<br />With the exception of brief update periods, Android has been available under a free software/open source li...
Code Access<br />Parts<br />Kernel<br />Android Open Source Project (AOSP)<br />Kernel<br />Should have access to latest s...
Code Licenses<br />Kernel<br />GNU General Public License (a.k.a. GPL)<br />AOSP<br />Mostly Apache License 2.0 (a.k.a. AS...
Versions<br />Ice Cream Sandwich<br />
Version History<br />2008 - Sept.: Android 1.0 is released<br />2009 - Feb.: Android 1.1<br />2009 - Apr.: Android 1.5 / C...
ANDROID BASICS<br />
What is Android<br />Android is a software stack for mobile devices that includes an operating system, middleware and key ...
Android Software Stack<br />
Linux kernel<br />Android built on Linux 2.6 kernel <br />Provides security, memory management, process management, networ...
Linux kernel – Androidsm<br />
Libraries<br />A set of C/C++ libraries exposed to developers through the application framework<br />
Libraries<br />System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded...
Libraries<br />Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layer...
Libraries<br />LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view<b...
Libraries<br />3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D accelera...
Dalvik Virtual Machine<br />Runtime libraries provide most of the functionality in the core Java libraries <br />Each app ...
Application Framework<br />The framework allows developers to build cool apps<br />
Application Framework<br />Core System services<br />Activity manager (manages application lifecycle)<br />Package manager...
Applications<br />AOSP and Non-AOSP Apps<br />
Applications<br />The non-AOSP apps<br />Android Market<br />YouTube<br />Maps and Navigation<br />Gmail<br />Voice<br />S...
ANDROID APPLICATION FUNDAMENTALS<br />
Application - User Interaction<br />
Screen Characteristics<br />Screen size<br />Screen density<br />Orientation<br />Resolution<br />Density-independent pixe...
Screen size & Density<br />Actual physical size, measured as the screen's diagonal. <br />The quantity of pixels within a ...
Orientation<br />Landscape<br />Portrait<br />
Resolution<br />The total number of physical pixels on a screen. <br />When adding support for multiple screens, applicati...
Density-independent pixel (dp)<br />A virtual pixel unit that you should use when defining UI layout, to express layout di...
Density Dependence<br />Example application without support for different densities, as shown on low, medium, and high den...
Alternative drawables<br />36x36 for low-density<br />48x48 for medium-density<br />72x72 for high-density<br />96x96 for ...
Screen Configuration<br />
Screen Configuration<br />
Application Fundamentals<br />Android applications are written in the Java programming language.<br />The Android SDK tool...
Security Sandbox<br />Once installed on a device, each Android application lives in its own security sandbox: <br />The An...
Sharing Data<br />However, there are ways for an application to share data with other applications and for an application ...
What makes an Android Application<br />The core framework components that define your application.<br />The manifest file ...
Application Components<br />Application components are the essential building blocks of an Android application.<br />Each ...
Types of application components<br />Activities<br />Services<br />Content providers<br />Broadcast receivers<br />
Activities<br />An activity represents a single screen with a user interface<br />Example of Activities in Email Applicati...
Activities<br />
Services<br />A service is a component that runs in the background to perform long-running operations or to perform work f...
Services<br />
Content Provider<br />A content provider manages a shared set of application data.<br />You can store the data in the file...
Broadcast Receiver<br />A broadcast receiver is a component that responds to system-wide broadcast announcements.<br />Man...
Androidism<br />Any application can start another application’s component.<br />No “main()” function<br />Intent<br />
Start Another Application<br />A unique aspect of the Android system design is that any application can start another appl...
Start Another Application<br />FACEBOOK APP<br />(PROCESS P1)<br />FACEBOOK APP<br />(PROCESS P1)<br />CAMERA APP<br />(PR...
No MAIN()<br />When the system starts a component, it starts the process for that application (if it's not already running...
No MAIN()<br />APP 2<br />(PROCESS P2)<br />APP 1<br />(PROCESS P1)<br />Camera Settings<br />Some Activity<br />Capture P...
Intent<br />Because the system runs each application in a separate process with file permissions that restrict access to o...
Intent<br />Intent to Download<br />
Activating Components<br />Three of the four component types—activities, services, and broadcast receivers—are activated b...
Activating Components<br />For activities and services, an intent defines the action to perform (for example, to "view" or...
Activating Components<br />Content provider, is not activated by intents. <br />It is activated when targeted by a request...
Manifest File<br />Before the Android system can start an application component, the system must know that the component e...
Manifest File<br />The manifest does a number of things in addition to declaring the application's components, such as:<br...
Declaring components<br />
Declaring components<br />You must declare all application components this way:<br /><activity> elements for activities<br...
Declaring component capabilities<br />You can use an Intent to start activities, services, and broadcast receivers.<br />C...
Declaring component capabilities<br />The way the system identifies the components that can respond to an intent is by com...
Declaring application requirements<br />There are a variety of devices powered by Android and not all of them provide the ...
Declaring application requirements<br />Important device characteristics<br />Screen size and density<br />Input configura...
Screen size and density<br />In order to categorize devices by their screen type, Android defines two characteristics for ...
Input configurations<br />Many devices provide a different type of user input mechanism, such as a hardware keyboard, a tr...
Device features<br />There are many hardware and software features that may or may not exist on a given Android-powered de...
Platform Version<br />Different Android-powered devices often run different versions of the Android platform, such as Andr...
API Level <br />API Level is an integer value that uniquely identifies the framework API revision offered by a version of ...
API Level <br />Updates to the framework API are designed so that the new API remains compatible with earlier versions of ...
API Level <br />
Application Resources<br />An Android application is composed of more than just code—it requires resources that are separa...
Application Resources<br />For every resource that you include in your Android project, the SDK build tools define a uniqu...
Application Resources<br />Same ID (R.ID)<br />but different Resource<br />
DEVELOPING APPLICATIONS<br />
Tools<br />Eclipse<br />Android Development Tools (ADT)<br />SDK<br />NDK<br />
Steps<br />Set up Android Virtual Devices or hardware devices<br />Create an Android project<br />Build and run your appli...
Tutorial<br />Hello World <br />
ACTIVITIES<br />
Activity<br />An Activity is an application component that provides a screen with which users can interact in order to do ...
Activity<br />An application usually consists of multiple activities that are loosely bound to each other<br />Typically, ...
Back Stack<br />Each time a new activity starts, the previous activity is stopped, but the system preserves the activity i...
Back Stack<br />
Back Stack<br />Two tasks: Task A is in the background, waiting to be resumed, while Task B receives user interaction in t...
Back Stack<br />A single activity is instantiated multiple times<br />
Creating Activity<br />Subclasss the Activity class<br />Implement User Interface<br />Declare Activity in the manifest<br />
Sub class<br />To create an activity, you must create a subclass of Activity (or an existing subclass of it). <br />In you...
Implement UI<br />The user interface for an activity is provided by a hierarchy of views—objects derived from the View cla...
Implement UI<br />Android provides a number of ready-made views that you can use to design and organize your layout. <br /...
View & View Groups<br />Widget<br />Layout<br />
Define UI<br />The most common way to define a layout using views is with an XML layout file saved in your application res...
Define UI<br />
Creating Activity – Manifest<br />You must declare your activity in the manifest file in order for it to be accessible to ...
Creating Activity – Manifest<br />There are several other attributes that you can include in this element, to define prope...
Intent Filters<br />An <activity> element can also specify various intent filters—using the <intent-filter> element—in ord...
Intent Filters<br />If you intend for your application to be self-contained and not allow other applications to activate i...
Lab <br />Hello World Tutorial<br />
Starting an Activity<br />You can start another activity by calling startActivity(), passing it an Intent that describes t...
Starting an Activity<br />When working within your own application, you'll often need to simply launch a known activity. Y...
Lab <br />Create a new activity<br />Start a new activity from the Main activity<br />
Starting an Activity<br />your application might also want to perform some action, such as send an email, text message, or...
Lab<br />Create a new activity<br />Start the new activity from Main activity<br />Pass data to new activity<br />
Starting an activity for a result<br />Sometimes, you might want to receive a result from the activity that you start. <br...
Shutting Down an Activity<br />You can shut down an activity by calling its finish() method. You can also shut down a sepa...
Lab<br />Create a new activity<br />Start the new activity for result from Main activity<br />Get result from new activity...
Managing the Activity Lifecycle<br />An activity can exist in essentially three states:<br />Resumed The activity is in th...
Implementing the lifecycle callbacks<br />When an activity transitions into and out of the different states described abov...
Implementing the lifecycle callbacks<br />
Activity Lifecycle<br />
Saving persistent Data<br />The activity is killable after-<br />onPause()<br />onStop()<br />onDestroyed()<br />onPause()...
Lab<br />Saving Activity Data<br />LunarLander<br />
Saving activity state<br />when an activity is paused or stopped, the state of the activity is retained. This is true beca...
Saving activity state<br />
Saving activity state<br />The callback method in which you can save information about the current state of your activity ...
Saving activity state<br />Even if you do nothing and do not implement onSaveInstanceState(), some of the activity state i...
Handling configuration changes<br />Some device configurations can change during runtime (such as screen orientation, keyb...
Lab<br />Saving Activity State<br />Default onSaveInstanceState() Behavior<br />
Handling Runtime Changes<br />Some device configurations can change during runtime (such as screen orientation, keyboard a...
Handling Runtime Changes<br />If restarting your Activity requires that you recover large sets of data, re-establish a net...
Handling Runtime Changes<br />To retain an Object during a runtime configuration change:<br />Override the onRetainNonConf...
Handling Runtime Changes<br />
Activity Summary<br />Activity Lifecycle<br />Save persistent data<br />Save persistent state<br />Handle runtime configur...
USER INTERFACE<br />
User Interface<br />In an Android application, the user interface is built using View and ViewGroup objects. There are man...
User Interface<br />A View object is a data structure whose properties store the layout parameters and content for a speci...
View & View Groups<br />Widget<br />Layout<br />
View Hierarchy<br />
View Hierarchy<br />In order to attach the view hierarchy tree to the screen for rendering, your Activity must call the se...
Layout<br />Your layout is the architecture for the user interface in an Activity. <br />It defines the layout structure a...
Layout<br />The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your a...
Declaring Layout<br />The most common way to define your layout and express the view hierarchy is with an XML layout file....
Declaring Layout<br />
Declaring Layout<br />The name of an XML element is respective to the Java class that it represents. So a <TextView> eleme...
Declaring Layout<br />Each layout file must contain exactly one root element, which must be a View or ViewGroup object. On...
Loading Layout<br />When you compile your application, each XML layout file is compiled into a View resource. <br />You sh...
XML Attributes<br />Every View and ViewGroup object supports their own variety of XML attributes. <br />Some attributes ar...
ID<br />Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. <br />Wh...
Android Framework ID<br />There are a number of other ID resources that are offered by the Android framework. <br />When r...
Defining & Accessing Views<br />In order to create views and reference them from the application, a common pattern is to:<...
Layout Parameters<br />Visualization of a view hierarchy with layout parameters associated with each view.<br />
Layout Parameters<br />XML layout attributes named layout_something define layout parameters for the View that are appropr...
Layout Parameters<br />You can specify width and height with exact measurements, though you probably won't want to do this...
Layout Position<br />The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and...
Layout Position<br />getTop()<br />getBottom()<br />getLeft()<br />View<br />getRight()<br />Parent<br />
Size, Padding and Margins<br />
Size, Padding and Margins<br />The size of a view is expressed with a width and a height. A view actually possess pairs of...
Common layout Objects<br />
Common layout Objects<br />
Linear layout<br />
Table Layout<br />
Relative Layout<br />
Lab<br />XML & Layout Window<br />Layouts<br />Linear<br />Relative<br />Table<br />Grid<br />Tab<br />List<br />
Widgets<br />A widget is a View object that serves as an interface for interaction with the user. Android provides a set o...
Widgets<br />
Lab<br />Widgets<br /><ul><li>Date Picker
Time Picker
Form Stuff
Spinner
Auto Complete
Gallery
Web View</li></li></ul><li>UI Events<br />Once you've added some Views/widgets to the UI, you probably want to know about ...
Event Listener<br />An event listener is an interface in the View class that contains a single callback method. These meth...
Example register an on-click listener for a Button<br />
Example - OnClickListener as a part of your Activity<br />
Listener Return Value<br />Notice that the onClick() callback in the above example has no return value, but some other eve...
Touch Mode<br />When a user is navigating a user interface with directional keys or a trackball, it is necessary to give f...
Menus<br />Menus reveals application functions and settings. <br />The most common application menu is revealed by pressin...
Menus<br />
Creating a Menu Resource<br />Instead of instantiating a Menu in your application code, you should define a menu and all i...
Creating a Menu Resource<br />
Creating a Menu Resource<br />To create a menu resource, create an XML file inside your project's res/menu/ directory and ...
Inflating a Menu Resource<br />From your application code, you can inflate a menu resource (convert the XML resource into ...
Creating an Options Menu<br />The Options Menu is where you should include basic activity actions and necessary navigation...
Creating an Options Menu<br />When the Android system creates the Options Menu for the first time, it calls your activity'...
Responding to user action<br />When the user selects a menu item from the Options Menu <br />the system calls your activit...
Lab<br />Create menu from XML<br />Handle user action<br />
Creating a Context Menu<br />A context menu is conceptually similar to the menu displayed when the user performs a "right-...
Creating a Context Menu<br />In order for a View to provide a context menu, you must "register" the view for a context men...
Creating a Context Menu<br />Get info for the selected item<br />
Lab<br />Create a context Menu<br />Handle user action<br />
Creating Submenus<br />A submenu is a menu that the user can open by selecting an item in another menu. <br />You can add ...
Creating Submenus<br />When creating your menu resource, you can create a submenu by adding a <menu> element as the child ...
Responding to user action<br />When the user selects an item from a submenu, the parent menu's respective on-item-selected...
Lab<br />Create sub menu<br />Handle user action<br />
Dialogs<br />A dialog is usually a small window that appears in front of the current Activity. <br />The underlying Activi...
Dialogs<br />The Dialog class is the base class for creating dialogs. However, you typically should not instantiate a Dial...
Creating an AlertDialog<br />An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog...
Creating an AlertDialog & Adding Buttons<br />To create an AlertDialog, use the AlertDialog.Builder subclass. <br />Get a ...
Adding a List<br />
Adding checkboxes and radio buttons<br />No item should <br />be selected by Default<br />
Creating a ProgressDialog<br />A ProgressDialog is an extension of the AlertDialog class that can display a progress anima...
Showing a progress bar<br />To show the progression with an animated progress bar:<br />Initialize the ProgressDialog with...
Lab<br />OK Cancel Dialog with a message<br />List Dialog<br />Progress Dialog<br />Single choice list<br />
User Notification<br />User different technique:<br />A Toast Notification, for brief messages that come from the backgrou...
Creating Toast Notifications<br />A toast notification is a message that pops up on the surface of the window. <br />It on...
Creating Toast Notifications<br />You can also chain your methods and avoid holding on to the Toast object, like this:<br />
Lab<br />Create Toast<br />
Status Bar Notifications<br />
Status Bar Notifications<br />A status bar notification adds an icon to the system's status bar (with an optional ticker-t...
Status Bar Notifications<br />A status bar notification should be used for any case in which a background Service needs to...
Creating Status Bar Notifications<br />Get a reference to the NotificationManager:<br />
Creating Status Bar Notifications<br />Instantiate the Notification:<br />
Creating Status Bar Notifications<br />Define the Notification's expanded message and Intent: <br />
Creating Status Bar Notifications<br />Pass the Notification to the NotificationManager: <br />
Adding Sound, vibration etc<br />notification.defaults |= Notification.DEFAULT_SOUND; <br />notification.defaults |= Notif...
Lab<br />App->Notification<br />
Adapters<br />Sometimes you'll want to populate a view group with some information that can't be hard-coded, instead, you ...
AdapterView<br />Gallery, ListView, and Spinner are examples of AdapterView subclasses that you can use to bind to a speci...
SimpleCursorAdapter<br />
SimpleCursorAdapter<br />SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)<br />This ada...
ArrayAdapter<br />ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,new  st...
Lab<br />Data for the list comes from an array of strings<br />Data comes from a cursor <br />Data comes from a custom Lis...
Styles and Themes<br />Perhaps you're not satisfied with the look of the standard widgets. To revise them, you can create ...
Styles and Themes<br />A style is a collection of properties that specify the look and format for a View or window. A styl...
Style<br />
Defining Style<br />To create a set of styles, save an XML file in the res/values/ directory of your project. The name of ...
Lab<br />Style<br />
APPLICATION MANIFEST<br />
Application Manifest<br />Every application must have an AndroidManifest.xml file (with precisely that name) in its root d...
Application Manifest<br />The manifest does the following: <br />It names the Java package for the application. The packag...
Structure of the Manifest File<br />
Elements of Manifest File<br /><action><activity><activity-alias><application><category><data><grant-uri-permission><instr...
Manifest Editor<br />Lab<br />
APPLICATION RESOURCES<br />
Application Resources<br />You should always externalize resources such as images and strings from your application code, ...
Application Resources<br />Two different devices, both using default resources<br />Two different devices, one using alter...
Providing Resources<br />
Providing Resources<br />
Providing Resources<br />
Providing Resources<br />
Providing Alternative Resources<br />Screen size<br />smallnormallargexlarge<br />Screen aspect<br />longnotlong<br /><ul>...
Screen pixel density (dpi)
ldpimdpihdpixhdpinodpi</li></li></ul><li>Accessing Resources<br />When your application is compiled, aapt generates the R ...
Accessing Resources<br />There are two ways you can access a resource:<br />In code: Using an static integer from a sub-cl...
Accessing Resources in Code<br />Here's the syntax to reference a resource in code:<br />[<package_name>.]R.<resource_type...
Use cases<br />
Accessing Resources from XML<br />Here is the syntax to reference a resource in an XML resource:<br />@[<package_name>:]<r...
Use Cases<br />
INTENTS<br />
Intents<br />Three of the core components of an application — activities, services, and broadcast receivers — are activate...
Delivering Intents<br />There are separate mechanisms for delivering intents to each type of component: <br />An Intent ob...
Delivering Intents<br />In each case, the Android system finds the appropriate activity, service, or set of broadcast rece...
Intent Objects<br />An Intent object is a bundle of information. <br />It contains information of interest to- <br />the c...
Intent Objects<br />Principally, Intent Object can contain the following: <br />Component name<br />Action<br />Data<br />...
Component Name<br />The name of the component that should handle the intent. <br />This field is a ComponentName object — ...
Component Name<br />The component name is optional. <br />If it is set, the Intent object is delivered to an instance of t...
Action<br />A string naming the action to be performed — or, in the case of broadcast intents, the action that took place ...
Action<br />You can also define your own action strings for activating the components in your application. <br />Those you...
Action<br />The action largely determines how the rest of the intent is structured — particularly the data and extras fiel...
Data<br />The URI of the data to be acted on and the MIME type of that data. <br />Different actions are paired with diffe...
Data<br />When matching an intent to a component that is capable of handling the data, it's often important to know the ty...
Category<br />A string containing additional information about the kind of component that should handle the intent. Any nu...
Category<br />The addCategory() method places a category in an Intent object, removeCategory() deletes a category previous...
Extras<br />Key-value pairs for additional information that should be delivered to the component handling the intent. <br ...
Flags<br />Flags of various sorts. <br />Many instruct the Android system how to launch an activity (for example, which ta...
Intent Resolution<br />Intents can be divided into two groups: <br />Explicit intentsdesignate the target component by its...
Implicit Intent Resolution<br />the Android system must find the best component (or components) to handle the intent — <br...
Implicit Intent Resolution<br />Only three aspects of an Intent object are consulted when the object is tested against an ...
Action test<br />To pass this test, the action specified in the Intent object must match one of the actions listed in the ...
Category test<br />For an intent to pass the category test, every category in the Intent object must match a category in t...
Data test<br />Each <data> element can specify a URI and a data type (MIME media type). <br />There are separate attribute...
Data test<br />When the URI in an Intent object is compared to a URI specification in a filter, it's compared only to the ...
Data test<br />The type attribute of a <data> element specifies the MIME type of the data. <br />It's more common in filte...
Data test<br />The rules are as follows: <br />An Intent object that contains neither a URI nor a data type passes the tes...
Lab<br />Create Intents to Launch system activities<br />Browser<br />Phone Dialer<br />Make Phone call<br />
SERVICES<br />
Service Lifetime<br />
Lab<br />Lab<br />
DATA STORAGE<br />
Data Storage<br />Android provides several options for you to save persistent application data. <br />The solution you cho...
Data Storage<br />Your data storage options are the following:<br />Shared Preferences Store private primitive data in key...
Shared Preferences<br />The SharedPreferences class provides a general framework that allows you to save and retrieve pers...
Using Shared Preferences<br />To get a SharedPreferences object for your application, use one of two methods:<br />getShar...
Using Shared Preferences<br />To write values:<br />Call edit() to get a SharedPreferences.Editor.<br />Add values with me...
Using Shared Preferences<br />Shared Preference <br />file name<br />Get Shared Preference<br />Each getter takes a key an...
Lab<br />Shared Preferences<br />
Internal Storage<br />You can save files directly on the device's internal storage. <br />By default, files saved to the i...
Using the Internal Storage<br />To create and write a private file to the internal storage<br />Call openFileOutput() with...
Using the Internal Storage<br />MODE_PRIVATE will create the file (or replace a file of the same name) and make it private...
Using the Internal Storage<br />To read a file from internal storage:<br />Call openFileInput() and pass it the name of th...
Lab<br />Internal Storage<br />
Using the External Storage<br />Every Android-compatible device supports a shared "external storage" that you can use to s...
Checking media availability<br />
Accessing files on external storage<br />use getExternalFilesDir() to open a File that represents the external storage dir...
Saving files that should be shared<br />If you want to save files that are not specific to your application and that shoul...
Saving files that should be shared<br />Music/ - Media scanner classifies all media found here as user music.<br />Podcast...
Lab<br />External Storage <br />
Using Databases<br />Android provides full support for SQLite databases. <br />Any databases you create will be accessible...
Using Databases<br />
Using Databases<br />You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've def...
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Android Application Development
Upcoming SlideShare
Loading in...5
×

Android Application Development

8,863

Published on

Training on Android SDK.

3 Comments
40 Likes
Statistics
Notes
No Downloads
Views
Total Views
8,863
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
352
Comments
3
Likes
40
Embeds 0
No embeds

No notes for slide

Android Application Development

  1. 1. ANDROID APPLICATION DEVELOPMENT<br />Ramesh Prasad<br />
  2. 2. INTRODUCTION<br />
  3. 3. Android Devices<br />
  4. 4. Mobile Operating System ?<br />
  5. 5. A BRIEF HISTORY OF ANDROID<br />
  6. 6. History<br />Android, Inc. was founded in Palo Alto, California, United States in October, 2003 by Andy Rubin and others<br />Googleacquired Android Inc. in August 2005, making Android Inc. a wholly owned subsidiary of Google Inc.<br />On November 5, 2007, the Open Handset Alliance, a consortium of several companies which include Broadcom Corporation, Google, HTC, Intel, LG, Marvell Technology Group, Motorola, Nvidia, Qualcomm, Samsung Electronics, Sprint Nextel, T-Mobile and Texas Instruments unveiled itself.<br />
  7. 7. Licensing<br />With the exception of brief update periods, Android has been available under a free software/open source license since October, 21 2008. Google published the entire source code (including network and telephony stacks) under an Apache License.<br />Even though the software is open-source, device manufacturers cannot use Google's Android trademark unless Google certifies that the device complies with their Compatibility Definition Document (CDD).<br />In early 2011, Google chose to temporarily withhold the source code to the tablet-only Honeycomb release.<br />Honeycomb source code would not be released until after it was merged with the Gingerbread release in Ice Cream Sandwich.<br />
  8. 8. Code Access<br />Parts<br />Kernel<br />Android Open Source Project (AOSP)<br />Kernel<br />Should have access to latest shipped version => GPL requirement<br />Google-maintained forks at android.git.kernel.org<br />AOSP<br />Usually Code-drops every 6 months<br />Official AOSP branches at android.git.kernel.org<br />
  9. 9. Code Licenses<br />Kernel<br />GNU General Public License (a.k.a. GPL)<br />AOSP<br />Mostly Apache License 2.0 (a.k.a. ASL)<br />Having GPL-free user-space was a design goal<br />A few GPL and LGPL parts: mainly BlueZ and DBUS<br />Some key components in BSD: Bionic and Toolbox<br />“external/” directory contains a mixed bag of licenses, incl. lots of GPL<br />
  10. 10. Versions<br />Ice Cream Sandwich<br />
  11. 11. Version History<br />2008 - Sept.: Android 1.0 is released<br />2009 - Feb.: Android 1.1<br />2009 - Apr.: Android 1.5 / Cupcake<br />2009 - Sept.: Android 1.6 / Donut<br />2009 - Oct.: Android 2.0/2.1 / Eclair<br />2010 - May: Android 2.2 / Froyo<br />2010 - Dec.: Android 2.3 / Gingerbread<br />2011 - Jan : Android 3.0 / Honeycomb – Tablet-optimized<br />2011 – May: Android 3.1 – USB host support<br />2011 – Dec: Android 4.0 / Ice-Cream Sandwich – merge Gingerbread and Honeycomb<br />
  12. 12. ANDROID BASICS<br />
  13. 13. What is Android<br />Android is a software stack for mobile devices that includes an operating system, middleware and key applications.<br />The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.<br />The Android NDK is a toolset that lets you embed components that make use of native code (C/C++) in your Android applications.<br />
  14. 14. Android Software Stack<br />
  15. 15. Linux kernel<br />Android built on Linux 2.6 kernel <br />Provides security, memory management, process management, network stack, and driver model <br />Abstraction layer between hardware and the software stack <br />
  16. 16. Linux kernel – Androidsm<br />
  17. 17. Libraries<br />A set of C/C++ libraries exposed to developers through the application framework<br />
  18. 18. Libraries<br />System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices<br />Media Libraries - based on PacketVideo'sOpenCORE; 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<br />
  19. 19. Libraries<br />Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications<br />FreeType - bitmap and vector font rendering<br />
  20. 20. Libraries<br />LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view<br />SGL - the underlying 2D graphics engine<br />
  21. 21. Libraries<br />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<br />SQLite - a powerful and lightweight relational database engine available to all applications <br />
  22. 22. Dalvik Virtual Machine<br />Runtime libraries provide most of the functionality in the core Java libraries <br />Each app has a process and an instance of Dalvik VM <br />Uses Dalvik Executable (.dex) format – low memory footprint <br />VM is register based runs compiled Java classes <br />The linux kernel provides Dalvik with needed functionality <br />
  23. 23. Application Framework<br />The framework allows developers to build cool apps<br />
  24. 24. Application Framework<br />Core System services<br />Activity manager (manages application lifecycle)<br />Package manager (loads apk files)<br />Window manager (handles applications window manager interaction<br /> with surface flinger)<br />Resource manager (handles media resources)<br />Content providers (provides data to application)<br />View system (provides widgets, views, layouts to applications)<br />Hardware services<br />Provides low-level access to hardware device<br />Location manager<br />Telephony manager<br />Bluetooth service<br />WiFi service / USB service / Sensor service<br />
  25. 25. Applications<br />AOSP and Non-AOSP Apps<br />
  26. 26. Applications<br />The non-AOSP apps<br />Android Market<br />YouTube<br />Maps and Navigation<br />Gmail<br />Voice<br />SkyMap<br />...<br />Require<br />CTS/CDD Compliance<br />Signed agreement w/ Google<br />
  27. 27. ANDROID APPLICATION FUNDAMENTALS<br />
  28. 28. Application - User Interaction<br />
  29. 29. Screen Characteristics<br />Screen size<br />Screen density<br />Orientation<br />Resolution<br />Density-independent pixel (dp)<br />
  30. 30. Screen size & Density<br />Actual physical size, measured as the screen's diagonal. <br />The quantity of pixels within a physical area of the screen; usually referred to as dpi (dots per inch). For example, a "low" density screen has fewer pixels within a given physical area, compared to a "normal" or "high" density screen.<br />
  31. 31. Orientation<br />Landscape<br />Portrait<br />
  32. 32. Resolution<br />The total number of physical pixels on a screen. <br />When adding support for multiple screens, applications do not work directly with resolution; applications should be concerned only with screen size and density, as specified by the generalized size and density groups.<br />
  33. 33. Density-independent pixel (dp)<br />A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. <br />The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. <br />At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. <br />The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. <br />You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities. <br />
  34. 34. Density Dependence<br />Example application without support for different densities, as shown on low, medium, and high density screens.<br />Example application with good support for different densities (it's density independent), as shown on low, medium, and high density screens<br />
  35. 35. Alternative drawables<br />36x36 for low-density<br />48x48 for medium-density<br />72x72 for high-density<br />96x96 for extra high-density<br />3:4:6:8 scaling ratio<br />res/drawable-mdpi/my_icon.png        // bitmap for medium densityres/drawable-hdpi/my_icon.png        // bitmap for high densityres/drawable-xhdpi/my_icon.png       // bitmap for extra high density<br />
  36. 36. Screen Configuration<br />
  37. 37. Screen Configuration<br />
  38. 38. Application Fundamentals<br />Android applications are written in the Java programming language.<br />The Android SDK tools compile the code—along with any data and resource files—into an Android package, an archive file with an .apk suffix. <br />All the code in a single .apk file is considered to be one application and is the file that Android-powered devices use to install the application.<br />
  39. 39. Security Sandbox<br />Once installed on a device, each Android application lives in its own security sandbox: <br />The Android operating system is a multi-user Linux system in which each application is a different user.<br />By default, the system assigns each application a unique Linux user ID (the ID is used only by the system and is unknown to the application). The system sets permissions for all the files in an application so that only the user ID assigned to that application can access them. <br />Each process has its own virtual machine (VM), so an application's code runs in isolation from other applications.<br />By default, every application runs in its own Linux process. Android starts the process when any of the application's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other applications.<br />
  40. 40. Sharing Data<br />However, there are ways for an application to share data with other applications and for an application to access system services:<br />It's possible to arrange for two applications to share the same Linux user ID, in which case they are able to access each other's files. To conserve system resources, applications with the same user ID can also arrange to run in the same Linux process and share the same VM (the applications must also be signed with the same certificate).<br />An application can request permission to access device data such as the user's contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All application permissions must be granted by the user at install time.<br />
  41. 41. What makes an Android Application<br />The core framework components that define your application.<br />The manifest file in which you declare components and required device features for your application.<br />Resources that are separate from the application code and allow your application to gracefully optimize its behavior for a variety of device configurations.<br />
  42. 42. Application Components<br />Application components are the essential building blocks of an Android application.<br />Each component is a different point through which the system can enter your application.<br />Not all components are actual entry points for the user <br />Each one exists as its own entity and plays a specific role—each one is a unique building block that helps define your application's overall behavior.<br />
  43. 43. Types of application components<br />Activities<br />Services<br />Content providers<br />Broadcast receivers<br />
  44. 44. Activities<br />An activity represents a single screen with a user interface<br />Example of Activities in Email Application-<br />Email List<br />Compose<br />Read<br />Etc..<br />Although the activities work together to form a cohesive user experience in the email application, each one is independent of the others.<br />A different application can start any one of these activities (if the email application allows it)<br />For example, a camera application can start the activity in the email application that composes new mail, in order for the user to share a picture.<br />
  45. 45. Activities<br />
  46. 46. Services<br />A service is a component that runs in the background to perform long-running operations or to perform work for remote processes.<br />A service does not provide a user interface.<br />For example, a service might play music in the background while the user is in a different application<br />
  47. 47. Services<br />
  48. 48. Content Provider<br />A content provider manages a shared set of application data.<br />You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your application can access.<br />Through the content provider, other applications can query or even modify the data (if the content provider allows it).<br />For example, the Android system provides a content provider that manages the user's contact information. As such, any application with the proper permissions can query part of the content provider to read and write information about a particular person.<br />
  49. 49. Broadcast Receiver<br />A broadcast receiver is a component that responds to system-wide broadcast announcements.<br />Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured.<br />Applications can also initiate broadcasts<br />Although broadcast receivers don't display a user interface, they may create a status bar notificationto alert the user when a broadcast event occurs.<br />
  50. 50. Androidism<br />Any application can start another application’s component.<br />No “main()” function<br />Intent<br />
  51. 51. Start Another Application<br />A unique aspect of the Android system design is that any application can start another application’s component. <br />For example, if you want the user to capture a photo with the device camera, there's probably another application that does that and your application can use it, instead of developing an activity to capture a photo yourself. <br />You don't need to incorporate or even link to the code from the camera application. <br />Instead, you can simply start the activity in the camera application that captures a photo. <br />When complete, the photo is even returned to your application so you can use it. <br />To the user, it seems as if the camera is actually a part of your application.<br />
  52. 52. Start Another Application<br />FACEBOOK APP<br />(PROCESS P1)<br />FACEBOOK APP<br />(PROCESS P1)<br />CAMERA APP<br />(PROCESS P2)<br />
  53. 53. No MAIN()<br />When the system starts a component, it starts the process for that application (if it's not already running) and instantiates the classes needed for the component.<br />For example, if your application starts the activity in the camera application that captures a photo, that activity runs in the process that belongs to the camera application, not in your application's process. Therefore, unlike applications on most other systems, Android applications don't have a single entry point (there's no main() function, for example).<br />
  54. 54. No MAIN()<br />APP 2<br />(PROCESS P2)<br />APP 1<br />(PROCESS P1)<br />Camera Settings<br />Some Activity<br />Capture Photo<br />Save Photo<br />Use Photo<br />
  55. 55. Intent<br />Because the system runs each application in a separate process with file permissions that restrict access to other applications, your application cannot directly activate a component from another application.<br />
  56. 56. Intent<br />Intent to Download<br />
  57. 57. Activating Components<br />Three of the four component types—activities, services, and broadcast receivers—are activated by an asynchronous message called an intent. <br />Intents bind individual components to each other at runtime (you can think of them as the messengers that request an action from other components), whether the component belongs to your application or another.<br />
  58. 58. Activating Components<br />For activities and services, an intent defines the action to perform (for example, to "view" or "send" something) and may specify the URI of the data to act. <br />For example, an intent might convey a request for an activity to show an image or to open a web page. <br />In some cases, you can start an activity to receive a result, in which case, the activity also returns the result in an Intent<br />For broadcast receivers, the intent simply defines the announcement being broadcast <br />
  59. 59. Activating Components<br />Content provider, is not activated by intents. <br />It is activated when targeted by a request from a ContentResolver. <br />The content resolver handles all direct transactions with the content provider so that the component that's performing transactions with the provider doesn't need to and instead calls methods on the ContentResolver object. <br />This leaves a layer of abstraction between the content provider and the component requesting information (for security).<br />
  60. 60. Manifest File<br />Before the Android system can start an application component, the system must know that the component exists by reading the application's AndroidManifest.xml file (the "manifest" file). <br />Your application must declare all its components in this file, which must be at the root of the application project directory.<br />Activities, services, and content providers that you include in your source but do not declare in the manifest are not visible to the system and, consequently, can never run. <br />However, broadcast receivers can be either declared in the manifest or created dynamically in code.<br />
  61. 61. Manifest File<br />The manifest does a number of things in addition to declaring the application's components, such as:<br />Identify any user permissions the application requires, such as Internet access or read-access to the user's contacts.<br />Declare the minimum API Level required by the application, based on which APIs the application uses.<br />Declare hardware and software features used or required by the application, such as a camera, bluetooth services, or a multitouch screen.<br />API libraries the application needs to be linked against (other than the Android framework APIs), such as the Google Maps library.<br />And more<br />
  62. 62. Declaring components<br />
  63. 63. Declaring components<br />You must declare all application components this way:<br /><activity> elements for activities<br /><service> elements for services<br /><receiver> elements for broadcast receivers<br /><provider> elements for content providers<br />
  64. 64. Declaring component capabilities<br />You can use an Intent to start activities, services, and broadcast receivers.<br />Can be done by explicitly naming the target component (using the component class name) in the intent. <br />However, the real power of intents lies in the concept of intent actions. <br />With intent actions, you simply describe the type of action you want to perform (and optionally, the data upon which you’d like to perform the action) and allow the system to find a component on the device that can perform the action and start it.<br />If there are multiple components that can perform the action described by the intent, then the user selects which one to use.<br />
  65. 65. Declaring component capabilities<br />The way the system identifies the components that can respond to an intent is by comparing the intent received to the intent filtersprovided in the manifest file of other applications on the device.<br />When you declare a component in your application's manifest, you can optionally include intent filters that declare the capabilities of the component so it can respond to intents from other applications.<br />For example, an email application with an activity for composing a new email might declare an intent filter in its manifest entry to respond to "send" intents (in order to send email). An activity in your application can then create an intent with the “send” action (ACTION_SEND), which the system matches to the email application’s “send” activity and launches it when you invoke the intent with startActivity().<br />
  66. 66. Declaring application requirements<br />There are a variety of devices powered by Android and not all of them provide the same features and capabilities. <br />In order to prevent your application from being installed on devices that lack features needed by your application, it's important that you clearly define a profile for the types of devices your application supports by declaring device and software requirements in your manifest file. <br />Most of these declarations are informational only and the system does not read them, but external services such as Android Market do read them in order to provide filtering for users when they search for applications from their device.<br />
  67. 67. Declaring application requirements<br />Important device characteristics<br />Screen size and density<br />Input configurations<br />Device features<br />Platform Version<br />
  68. 68. Screen size and density<br />In order to categorize devices by their screen type, Android defines two characteristics for each device: <br />screen size (the physical dimensions of the screen) and <br />screen density (the physical density of the pixels on the screen, or dpi—dots per inch). <br />To simplify all the different types of screen configurations, the Android system generalizes them into select groups that make them easier to target. The screen sizes are: small, normal, large, and extra large.<br />The screen densities are: low density, medium density, high density, and extra high density.<br />By default, your application is compatible with all screen sizes and densities, because the Android system makes the appropriate adjustments to your UI layout and image resources. <br />However, you should create specialized layouts for certain screen sizes and provide specialized images for certain densities, using alternative layout resources, and by declaring in your manifest exactly which screen sizes your application supports with the <supports-screens> element.<br />
  69. 69. Input configurations<br />Many devices provide a different type of user input mechanism, such as a hardware keyboard, a trackball, or a five-way navigation pad. If your application requires a particular kind of input hardware, then you should declare it in your manifest with the <uses-configuration> element.<br />
  70. 70. Device features<br />There are many hardware and software features that may or may not exist on a given Android-powered device, such as a camera, a light sensor, bluetooth, a certain version of OpenGL, or the fidelity of the touchscreen. <br />You should never assume that a certain feature is available on all Android-powered devices (other than the availability of the standard Android library), so you should declare any features used by your application with the <uses-feature> element.<br />
  71. 71. Platform Version<br />Different Android-powered devices often run different versions of the Android platform, such as Android 1.6 or Android 2.3. <br />Each successive version often includes additional APIs not available in the previous version. In order to indicate which set of APIs are available, each platform version specifies an API Level<br />If you use any APIs that were added to the platform after version 1.0, you should declare the minimum API Level in which those APIs were introduced using the <uses-sdk> element.<br />
  72. 72. API Level <br />API Level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform.<br />The framework API consists of:<br />A core set of packages and classes<br />A set of XML elements and attributes for declaring a manifest file<br />A set of XML elements and attributes for declaring and accessing resources<br />A set of Intents<br />A set of permissions that applications can request, as well as permission enforcements included in the system<br />
  73. 73. API Level <br />Updates to the framework API are designed so that the new API remains compatible with earlier versions of the API. That is, most changes in the API are additive and introduce new or replacement functionality.<br />The framework API that an Android platform delivers is specified using an integer identifier called "API Level". <br />Each Android platform version supports exactly one API Level, although support is implicit for all earlier API Levels (down to API Level 1). <br />
  74. 74. API Level <br />
  75. 75. Application Resources<br />An Android application is composed of more than just code—it requires resources that are separate from the source code, such as images, audio files, and anything relating to the visual presentation of the application.<br />you should define animations, menus, styles, colors, and the layout of activity user interfaces with XML files.<br />Using application resources makes it easy to update various characteristics of your application without modifying code and—by providing sets of alternative resources—enables you to optimize your application for a variety of device configurations (such as different languages and screen sizes).<br />
  76. 76. Application Resources<br />For every resource that you include in your Android project, the SDK build tools define a unique integer ID, which you can use to reference the resource from your application code or from other resource<br />One of the most important aspects of providing resources separate from your source code is the ability for you to provide alternative resources for different device configurations. sources defined in XML. <br />For example, by defining UI strings in XML, you can translate the strings into other languages and save those strings in separate files. Then, based on a language qualifier that you append to the resource directory's name (such as res/values-fr/ for French string values) and the user's language setting, the Android system applies the appropriate language strings to your UI.<br />
  77. 77. Application Resources<br />Same ID (R.ID)<br />but different Resource<br />
  78. 78. DEVELOPING APPLICATIONS<br />
  79. 79. Tools<br />Eclipse<br />Android Development Tools (ADT)<br />SDK<br />NDK<br />
  80. 80. Steps<br />Set up Android Virtual Devices or hardware devices<br />Create an Android project<br />Build and run your application<br />Debug your application with the SDK debugging and logging tools<br />Test your application with the Testing and Instrumentation framework<br />
  81. 81. Tutorial<br />Hello World <br />
  82. 82. ACTIVITIES<br />
  83. 83. Activity<br />An Activity is an application component that provides a screen with which users can interact in order to do something<br />Each activity is given a window in which to draw its user interface. <br />The window typically fills the screen, but may be smaller than the screen and float on top of other windows.<br />
  84. 84. Activity<br />An application usually consists of multiple activities that are loosely bound to each other<br />Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time.<br />Each activity can then start another activity in order to perform different actions.<br />
  85. 85. Back Stack<br />Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). <br />When a new activity starts, it is pushed onto the back stack and takes user focus. <br />The back stack abides to the basic "last in, first out" queue mechanism, so, when the user is done with the current activity and presses the BACK key, it is popped from the stack (and destroyed) and the previous activity resumes. <br />
  86. 86. Back Stack<br />
  87. 87. Back Stack<br />Two tasks: Task A is in the background, waiting to be resumed, while Task B receives user interaction in the foreground<br />
  88. 88. Back Stack<br />A single activity is instantiated multiple times<br />
  89. 89. Creating Activity<br />Subclasss the Activity class<br />Implement User Interface<br />Declare Activity in the manifest<br />
  90. 90. Sub class<br />To create an activity, you must create a subclass of Activity (or an existing subclass of it). <br />In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed.<br />
  91. 91. Implement UI<br />The user interface for an activity is provided by a hierarchy of views—objects derived from the View class. <br />Each view controls a particular rectangular space within the activity's window and can respond to user interaction. <br />For example, a view might be a button that initiates an action when the user touches it.<br />
  92. 92. Implement UI<br />Android provides a number of ready-made views that you can use to design and organize your layout. <br />"Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image. <br />"Layouts" are views derived from ViewGroup that provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout. <br />You can also subclass the View and ViewGroup classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.<br />
  93. 93. View & View Groups<br />Widget<br />Layout<br />
  94. 94. Define UI<br />The most common way to define a layout using views is with an XML layout file saved in your application resources. <br />This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior.<br />
  95. 95. Define UI<br />
  96. 96. Creating Activity – Manifest<br />You must declare your activity in the manifest file in order for it to be accessible to the system. To declare your activity, open your manifest file and add an <activity> element as a child of the <application> element.<br /><manifest ... > <br /> <application ... > <br /><activity android:name=".ExampleActivity" /> ... </application ... > <br />... </manifest > <br />
  97. 97. Creating Activity – Manifest<br />There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity's UI. <br />The android:name attribute is the only required attribute—it specifies the class name of the activity.<br />
  98. 98. Intent Filters<br />An <activity> element can also specify various intent filters—using the <intent-filter> element—in order to declare how other application components may activate it.<br />When you create a new application using the Android SDK tools, the stub activity that's created for you automatically includes an intent filter that declares the activity responds to the "main" action and should be placed in the "launcher" category. The intent filter looks like this:<br /><activity android:name=".ExampleActivity" android:icon="@drawable/app_icon"><br /> <intent-filter> <br /><action android:name="android.intent.action.MAIN" /> <br /><category android:name="android.intent.category.LAUNCHER" /> <br /></intent-filter> <br /></activity> <br />The <action> element specifies that this is the "main" entry point to the application. The <category> element specifies that this activity should be listed in the system's application launcher (to allow users to launch this activity).<br />
  99. 99. Intent Filters<br />If you intend for your application to be self-contained and not allow other applications to activate its activities, then you don't need any other intent filters. Only one activity should have the "main" action and "launcher" category, as in the previous example. <br />Activities that you don't want to make available to other applications should have no intent filters and you can start them yourself using explicit intents (as discussed in the following section).<br />However, if you want your activity to respond to implicit intents that are delivered from other applications (and your own), then you must define additional intent filters for your activity. <br />For each type of intent to which you want to respond, you must include an <intent-filter> that includes an <action> element and, optionally, a <category> element and/or a <data> element. These elements specify the type of intent to which your activity can respond.<br />
  100. 100. Lab <br />Hello World Tutorial<br />
  101. 101. Starting an Activity<br />You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. The intent specifies either-<br /> the exact activity you want to start or <br />describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different application). <br />An intent can also carrysmall amounts of data to be used by the activity that is started.<br />
  102. 102. Starting an Activity<br />When working within your own application, you'll often need to simply launch a known activity. You can do so by creating an intent that explicitly defines the activity you want to start, using the class name. <br />For example, here's how one activity starts another activity named SignInActivity:<br />Intent intent = new Intent(this, SignInActivity.class); <br />startActivity(intent); <br />
  103. 103. Lab <br />Create a new activity<br />Start a new activity from the Main activity<br />
  104. 104. Starting an Activity<br />your application might also want to perform some action, such as send an email, text message, or status update, using data from your activity<br />Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); <br />startActivity(intent); <br />
  105. 105. Lab<br />Create a new activity<br />Start the new activity from Main activity<br />Pass data to new activity<br />
  106. 106. Starting an activity for a result<br />Sometimes, you might want to receive a result from the activity that you start. <br />In that case, start the activity by calling startActivityForResult() (instead of startActivity()). <br />To then receive the result from the subsequent activity, implement the onActivityResult() callback method. <br />When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.<br />
  107. 107. Shutting Down an Activity<br />You can shut down an activity by calling its finish() method. You can also shut down a separate activity that you previously started by calling finishActivity().<br />Note: In most cases, you should not explicitly finish an activity using these methods. As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance of the activity.<br />
  108. 108. Lab<br />Create a new activity<br />Start the new activity for result from Main activity<br />Get result from new activity<br />
  109. 109. Managing the Activity Lifecycle<br />An activity can exist in essentially three states:<br />Resumed The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)<br />Paused Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. A paused activity is completely alive (the Activity object is retained in memory, it maintains all state and member information, and remains attached to the window manager), but can be killed by the system in extremely low memory situations.<br />Stopped The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.<br />
  110. 110. Implementing the lifecycle callbacks<br />When an activity transitions into and out of the different states described above, it is notified through various callback methods. All of the callback methods are hooks that you can override to do appropriate work when the state of your activity changes.<br />
  111. 111. Implementing the lifecycle callbacks<br />
  112. 112. Activity Lifecycle<br />
  113. 113. Saving persistent Data<br />The activity is killable after-<br />onPause()<br />onStop()<br />onDestroyed()<br />onPause() is the last method that's guaranteed to be called before the process can be killed—if the system must recover memory in an emergency, then onStop() and onDestroy() might not be called.<br />Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage. <br />However, you should be selective about what information must be retained during onPause(), because any blocking procedures in this method block the transition to the next activity and slow the user experience.<br />
  114. 114. Lab<br />Saving Activity Data<br />LunarLander<br />
  115. 115. Saving activity state<br />when an activity is paused or stopped, the state of the activity is retained. This is true because the Activity object is still held in memory when it is paused or stopped—all information about its members and current state is still alive. Thus, any changes the user made within the activity are retained in memory, so that when the activity returns to the foreground (when it "resumes"), those changes are still there.<br />However, when the system destroys an activity in order to recover memory, the Activity object is destroyed, so the system cannot simply resume it with its state intact. Instead, the system must recreate the Activity object if the user navigates back to it. Yet, the user is unaware that the system destroyed the activity and recreated it and, thus, probably expects the activity to be exactly as it was. <br />
  116. 116. Saving activity state<br />
  117. 117. Saving activity state<br />The callback method in which you can save information about the current state of your activity is onSaveInstanceState(). <br />The system calls this method before making the activity vulnerable to being destroyed and passes it a Bundle object. <br />The Bundle is where you can store state information about the activity as name-value pairs, using methods such as putString(). <br />Then, if the system kills your activity's process and the user navigates back to your activity, the system passes the Bundle to onCreate() so you can restore the activity state you saved during onSaveInstanceState(). <br />If there is no state information to restore, then the Bundle passed to onCreate() is null.<br />
  118. 118. Saving activity state<br />Even if you do nothing and do not implement onSaveInstanceState(), some of the activity state is restored by the Activity class's default implementation of onSaveInstanceState().<br />Specifically, the default implementation calls onSaveInstanceState() for every View in the layout, which allows each view to provide information about itself that should be saved. <br />Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved and restored when your activity is recreated.<br />For example, the EditText widget saves any text entered by the user and the CheckBox widget saves whether it's checked or not. The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. <br />If a widget does not have an ID, then it cannot save its state.<br />
  119. 119. Handling configuration changes<br />Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). <br />When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed immediately by onCreate()). <br />The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources that you've provided. <br />The best way to handle a configuration change, such as a change in the screen orientation, is to simply preserve the state of your application using onSaveInstanceState() and onRestoreInstanceState() (or onCreate())<br />
  120. 120. Lab<br />Saving Activity State<br />Default onSaveInstanceState() Behavior<br />
  121. 121. Handling Runtime Changes<br />Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When such a change occurs, Android restarts the running Activity (onDestroy() is called, followed by onCreate()). <br />The restart behavior is designed to help your application adapt to new configurations by automatically reloading your application with alternative resources.<br />Your application should be able to restart at any time without loss of user data or state<br />
  122. 122. Handling Runtime Changes<br />If restarting your Activity requires that you recover large sets of data, re-establish a network connection, or perform other intensive operations, then a full restart due to a configuration change might be an unpleasant user experience. <br />Also, it may not be possible for you to completely maintain your Activity state with the Bundle that the system saves for you during the Activity lifecycle—it is not designed to carry large objects (such as bitmaps) and the data within it must be serialized then deserialized, which can consume a lot of memory and make the configuration change slow. <br />In such a situation, you can alleviate the burden of reinitializing your Activity by retaining a stateful Object when your Activity is restarted due to a configuration change.<br />
  123. 123. Handling Runtime Changes<br />To retain an Object during a runtime configuration change:<br />Override the onRetainNonConfigurationInstance() method to return the Object you would like to retain.<br />Android calls onRetainNonConfigurationInstance() between onStop() and onDestroy() when it shuts down your Activity due to a configuration change.<br />When your Activity is created again, call getLastNonConfigurationInstance() to recover your Object.<br />
  124. 124. Handling Runtime Changes<br />
  125. 125. Activity Summary<br />Activity Lifecycle<br />Save persistent data<br />Save persistent state<br />Handle runtime configuration changes<br />
  126. 126. USER INTERFACE<br />
  127. 127. User Interface<br />In an Android application, the user interface is built using View and ViewGroup objects. There are many types of views and view groups, each of which is a descendant of the View class.<br />View objects are the basic units of user interface expression on the Android platform. <br />The View class serves as the base for subclasses called "widgets," which offer fully implemented UI objects, like text fields and buttons. <br />The ViewGroup class serves as the base for subclasses called "layouts," which offer different kinds of layout architecture, like linear, tabular and relative.<br />
  128. 128. User Interface<br />A View object is a data structure whose properties store the layout parameters and content for a specific rectangular area of the screen. <br />A View object handles its own measurement, layout, drawing, focus change, scrolling, and key/gesture interactions for the rectangular area of the screen in which it resides. <br />As an object in the user interface, a View is also a point of interaction for the user and the receiver of the interaction events.<br />
  129. 129. View & View Groups<br />Widget<br />Layout<br />
  130. 130. View Hierarchy<br />
  131. 131. View Hierarchy<br />In order to attach the view hierarchy tree to the screen for rendering, your Activity must call the setContentView() method and pass a reference to the root node object. The Android system receives this reference and uses it to invalidate, measure, and draw the tree. The root node of the hierarchy requests that its child nodes draw themselves — in turn, each view group node is responsible for calling upon each of its own child views to draw themselves.<br />Android parses the elements of your layout in-order (from the top of the hierarchy tree), instantiating the Views and adding them to their parent(s). Because these are drawn in-order, if there are elements that overlap positions, the last one to be drawn will lie on top of others previously drawn to that space.<br />
  132. 132. Layout<br />Your layout is the architecture for the user interface in an Activity. <br />It defines the layout structure and holds all the elements that appear to the user. <br />You can declare your layout in two ways:<br />Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.<br />Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically. <br />
  133. 133. Layout<br />The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior. Your UI descriptions are external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile. For example, you can create XML layouts for different screen orientations, different device screen sizes, and different languages.<br />Additionally, declaring the layout in XML makes it easier to visualize the structure of your UI, so it's easier to debug problems. As such, this document focuses on teaching you how to declare your layout in XML.<br />
  134. 134. Declaring Layout<br />The most common way to define your layout and express the view hierarchy is with an XML layout file. <br />Each element in XML is either a View or ViewGroup object (or descendant thereof). View objects are leaves in the tree, ViewGroup objects are branches in the tree<br />
  135. 135. Declaring Layout<br />
  136. 136. Declaring Layout<br />The name of an XML element is respective to the Java class that it represents. So a <TextView> element creates a TextView in your UI, and a <LinearLayout> element creates a LinearLayout view group. <br />When you load a layout resource, the Android system initializes these run-time objects, corresponding to the elements in your layout.<br />
  137. 137. Declaring Layout<br />Each layout file must contain exactly one root element, which must be a View or ViewGroup object. Once you've defined the root element, you can add additional layout objects or widgets as child elements to gradually build a View hierarchy that defines your layout.<br />After you've declared your layout in XML, save the file with the .xml extension, in your Android project's res/layout/ directory, so it will properly compile. <br />
  138. 138. Loading Layout<br />When you compile your application, each XML layout file is compiled into a View resource. <br />You should load the layout resource from your application code, in your Activity.onCreate() callback implementation. <br />Do so by calling setContentView(), passing it the reference to your layout resource in the form of: R.layout.layout_file_name<br />For example, if your XML layout is saved as main_layout.xml, you would load it for your Activity like so:<br />public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); <br />}<br />
  139. 139. XML Attributes<br />Every View and ViewGroup object supports their own variety of XML attributes. <br />Some attributes are specific to a View object (for example, TextView supports the textSize attribute)<br />Some are common to all View objects, because they are inherited from the root View class (like the id attribute). <br />And, other attributes are considered "layout parameters," which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object.<br />
  140. 140. ID<br />Any View object may have an integer ID associated with it, to uniquely identify the View within the tree. <br />When the application is compiled, this ID is referenced as an integer, but the ID is typically assigned in the layout XML file as a string, in the id attribute. <br />This is an XML attribute common to all View objects (defined by the View class) and you will use it very often. <br />The syntax for an ID, inside an XML tag is:<br />android:id="@+id/my_button" <br />The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource.<br />The plus-symbol (+) means that this is a new resource name that must be created and added to our resources (in the R.java file). <br />
  141. 141. Android Framework ID<br />There are a number of other ID resources that are offered by the Android framework. <br />When referencing an Android resource ID, you do not need the plus-symbol, but must add the android package namespace, like so:<br />android:id="@android:id/empty"<br />With the android package namespace in place, we're now referencing an ID from the android.R resources class, rather than the local resources class.<br />
  142. 142. Defining & Accessing Views<br />In order to create views and reference them from the application, a common pattern is to:<br />Define a view/widget in the layout file and assign it a unique ID: <br /><Button android:id="@+id/my_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/my_button_text"/> <br />Then create an instance of the view object and capture it from the layout (typically in the onCreate() method): <br />Button myButton = (Button) findViewById(R.id.my_button);<br />
  143. 143. Layout Parameters<br />Visualization of a view hierarchy with layout parameters associated with each view.<br />
  144. 144. Layout Parameters<br />XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides.<br />every LayoutParams subclass has its own syntax for setting values. Each child element must define LayoutParams that are appropriate for its parent, though it may also define different LayoutParams for its own children. <br />All view groups include a width and height (layout_width and layout_height), and each view is required to define them. <br />Many LayoutParams also include optional margins and borders. <br />
  145. 145. Layout Parameters<br />You can specify width and height with exact measurements, though you probably won't want to do this often. More often, you will use one of these constants to set the width or height: <br />wrap_content tells your view to size itself to the dimensions required by its content<br />fill_parent tells your view to become as big as its parent view group will allow.<br />In general, specifying a layout width and height using absolute units such as pixels is not recommended. Instead, using relative measurements such as density-independent pixel units (dp), wrap_content, or fill_parent, is a better approach, because it helps ensure that your application will display properly across a variety of device screen sizes. <br />
  146. 146. Layout Position<br />The geometry of a view is that of a rectangle. A view has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the pixel. <br />It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent. <br />In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth(). <br />
  147. 147. Layout Position<br />getTop()<br />getBottom()<br />getLeft()<br />View<br />getRight()<br />Parent<br />
  148. 148. Size, Padding and Margins<br />
  149. 149. Size, Padding and Margins<br />The size of a view is expressed with a width and a height. A view actually possess pairs of width and height values. <br />The pair is simply known as width and height, or sometimes drawing width and drawing height. These dimensions define the actual size of the view on screen, at drawing time and after layout. The width and height can be obtained by calling getWidth() and getHeight(). <br />To measure its dimensions, a view takes into account its padding. The padding is expressed in pixels for the left, top, right and bottom parts of the view. Padding can be used to offset the content of the view by a specific amount of pixels. For instance, a left padding of 2 will push the view's content by 2 pixels to the right of the left edge. Padding can be set using the setPadding(int, int, int, int) method and queried by calling getPaddingLeft(), getPaddingTop(), getPaddingRight() and getPaddingBottom(). <br />
  150. 150. Common layout Objects<br />
  151. 151. Common layout Objects<br />
  152. 152. Linear layout<br />
  153. 153. Table Layout<br />
  154. 154. Relative Layout<br />
  155. 155. Lab<br />XML & Layout Window<br />Layouts<br />Linear<br />Relative<br />Table<br />Grid<br />Tab<br />List<br />
  156. 156. Widgets<br />A widget is a View object that serves as an interface for interaction with the user. Android provides a set of fully implemented widgets, like buttons, checkboxes, and text-entry fields, so you can quickly build your UI.<br />Some widgets provided by Android are more complex, like a date picker, a clock, and zoom controls. But you're not limited to the kinds of widgets provided by the Android platform. <br />If you'd like to do something more customized and create your own actionable elements, you can, by defining your own View object or by extending and combining existing widgets.<br />
  157. 157. Widgets<br />
  158. 158. Lab<br />Widgets<br /><ul><li>Date Picker
  159. 159. Time Picker
  160. 160. Form Stuff
  161. 161. Spinner
  162. 162. Auto Complete
  163. 163. Gallery
  164. 164. Web View</li></li></ul><li>UI Events<br />Once you've added some Views/widgets to the UI, you probably want to know about the user's interaction with them, so you can perform actions. To be informed of UI events, you need to do one of two things:<br />Define an event listener and register it with the View. More often than not, this is how you'll listen for events. The View class contains a collection of nested interfaces named On<something>Listener, each with a callback method called On<something>(). For example, View.OnClickListener (for handling "clicks" on a View), View.OnTouchListener (for handling touch screen events in a View), and View.OnKeyListener (for handling device key presses within a View). So if you want your View to be notified when it is "clicked" (such as when a button is selected), implement OnClickListener and define its onClick() callback method (where you perform the action upon click), and register it to the View with setOnClickListener(). <br />Override an existing callback method for the View. This is what you should do when you've implemented your own View class and want to listen for specific events that occur within it.<br />
  165. 165. Event Listener<br />An event listener is an interface in the View class that contains a single callback method. These methods will be called by the Android framework when the View to which the listener has been registered is triggered by user interaction with the item in the UI.<br />Included in the event listener interfaces are the following callback methods:<br />onClick() From View.OnClickListener. This is called when the user either touches the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses the suitable "enter" key or presses down on the trackball. <br />onLongClick() From View.OnLongClickListener. This is called when the user either touches and holds the item (when in touch mode), or focuses upon the item with the navigation-keys or trackball and presses and holds the suitable "enter" key or presses and holds down on the trackball (for one second). <br />onFocusChange() From View.OnFocusChangeListener. This is called when the user navigates onto or away from the item, using the navigation-keys or trackball. <br />onKey() From View.OnKeyListener. This is called when the user is focused on the item and presses or releases a key on the device. <br />onTouch() From View.OnTouchListener. This is called when the user performs an action qualified as a touch event, including a press, a release, or any movement gesture on the screen (within the bounds of the item). <br />onCreateContextMenu() From View.OnCreateContextMenuListener. This is called when a Context Menu is being built (as the result of a sustained "long click"). <br />
  166. 166. Example register an on-click listener for a Button<br />
  167. 167. Example - OnClickListener as a part of your Activity<br />
  168. 168. Listener Return Value<br />Notice that the onClick() callback in the above example has no return value, but some other event listener methods must return a boolean. The reason depends on the event. For the few that do, here's why:<br />onLongClick() - This returns a boolean to indicate whether you have consumed the event and it should not be carried further. That is, returntrue to indicate that you have handled the event and it should stop here; return false if you have not handled it and/or the event should continue to any other on-click listeners.<br />onKey() - This returns a boolean to indicate whether you have consumed the event and it should not be carried further. That is, return true to indicate that you have handled the event and it should stop here; return false if you have not handled it and/or the event should continue to any other on-key listeners.<br />onTouch() - This returns a boolean to indicate whether your listener consumes this event. The important thing is that this event can have multiple actions that follow each other. So, if you return false when the down action event is received, you indicate that you have not consumed the event and are also not interested in subsequent actions from this event. Thus, you will not be called for any other actions within the event, such as a finger gesture, or the eventual up action event.<br />
  169. 169. Touch Mode<br />When a user is navigating a user interface with directional keys or a trackball, it is necessary to give focus to actionable items (like buttons) so the user can see what will accept input. If the device has touch capabilities, however, and the user begins interacting with the interface by touching it, then it is no longer necessary to highlight items, or give focus to a particular View. Thus, there is a mode for interaction named "touch mode." <br />For a touch-capable device, once the user touches the screen, the device will enter touch mode. From this point onward, only Views for which isFocusableInTouchMode() is true will be focusable, such as text editing widgets. Other Views that are touchable, like buttons, will not take focus when touched; they will simply fire their on-click listeners when pressed. <br />Any time a user hits a directional key or scrolls with a trackball, the device will exit touch mode, and find a view to take focus. Now, the user may resume interacting with the user interface without touching the screen. <br />
  170. 170. Menus<br />Menus reveals application functions and settings. <br />The most common application menu is revealed by pressing the MENU key on the device. <br />However, you can also add Context Menus, which may be revealed when the user presses and holds down on an item.<br />
  171. 171. Menus<br />
  172. 172. Creating a Menu Resource<br />Instead of instantiating a Menu in your application code, you should define a menu and all its items in an XML menu resource, then inflate the menu resource (load it as a programmable object) in your application code. <br />Using a menu resource to define your menu is a good practice because it separates the content for the menu from your application code. <br />It's also easier to visualize the structure and content of a menu in XML.<br />
  173. 173. Creating a Menu Resource<br />
  174. 174. Creating a Menu Resource<br />To create a menu resource, create an XML file inside your project's res/menu/ directory and build the menu with the following elements:<br /><menu> Defines a Menu, which is a container for menu items. A <menu> element must be the root node for the file and can hold one or more <item> and <group> elements. <br /><item> Creates a MenuItem, which represents a single item in a menu. This element may contain a nested <menu> element in order to create a submenu. <br /><group> An optional, invisible container for <item> elements. It allows you to categorize menu items so they share properties such as active state and visibility.<br />
  175. 175. Inflating a Menu Resource<br />From your application code, you can inflate a menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate(). <br />
  176. 176. Creating an Options Menu<br />The Options Menu is where you should include basic activity actions and necessary navigation items <br />the Options Menu appears at the bottom of the screen<br />When opened, the first visible portion of the Options Menu is the icon menu. It holds the first six menu items. <br />If you add more than six items to the Options Menu, Android places the sixth item and those after it into the overflow menu, which the user can open by touching the "More" menu item.<br />
  177. 177. Creating an Options Menu<br />When the Android system creates the Options Menu for the first time, it calls your activity's onCreateOptionsMenu() method. <br />Override this method in your activity and populate the Menu that is passed into the method, Menu by inflating a menu <br />
  178. 178. Responding to user action<br />When the user selects a menu item from the Options Menu <br />the system calls your activity's onOptionsItemSelected() method. This method passes the MenuItem that the user selected. You can identify the menu item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource). <br />You can match this ID against known menu items and perform the appropriate action.<br />Menu selection<br />handled<br />Menu selection<br />Not handled<br />
  179. 179. Lab<br />Create menu from XML<br />Handle user action<br />
  180. 180. Creating a Context Menu<br />A context menu is conceptually similar to the menu displayed when the user performs a "right-click" on a PC. <br />You should use a context menu to provide the user access to actions that pertain to a specific item in the user interface. <br />On Android, a context menu is displayed when the user performs a "long press" (press and hold) on an item.<br />
  181. 181. Creating a Context Menu<br />In order for a View to provide a context menu, you must "register" the view for a context menu. Call registerForContextMenu() and pass it the View you want to give a context menu. When this View then receives a long-press, it displays a context menu.<br />To define the context menu's appearance and behavior, override your activity's context menu callback methods, onCreateContextMenu() and onContextItemSelected().<br />
  182. 182. Creating a Context Menu<br />Get info for the selected item<br />
  183. 183. Lab<br />Create a context Menu<br />Handle user action<br />
  184. 184. Creating Submenus<br />A submenu is a menu that the user can open by selecting an item in another menu. <br />You can add a submenu to any menu (except a submenu).<br />Submenus are useful when your application has a lot of functions that can be organized into topics, like items in a PC application's menu bar (File, Edit, View, etc.).<br />
  185. 185. Creating Submenus<br />When creating your menu resource, you can create a submenu by adding a <menu> element as the child of an <item>.<br />
  186. 186. Responding to user action<br />When the user selects an item from a submenu, the parent menu's respective on-item-selected callback method receives the event. <br />For instance, if the above menu is applied as an Options Menu, then the onOptionsItemSelected() method is called when a submenu item is selected.<br />
  187. 187. Lab<br />Create sub menu<br />Handle user action<br />
  188. 188. Dialogs<br />A dialog is usually a small window that appears in front of the current Activity. <br />The underlying Activity loses focus and the dialog accepts all user interaction. <br />Dialogs are normally used for notifications that should interrupt the user and to perform short tasks that directly relate to the application in progress (such as a progress bar or a login prompt).<br />
  189. 189. Dialogs<br />The Dialog class is the base class for creating dialogs. However, you typically should not instantiate a Dialog directly. Instead, you should use one of the following subclasses:<br />AlertDialog A dialog that can manage zero, one, two, or three buttons, and/or a list of selectable items that can include checkboxes or radio buttons. The AlertDialog is capable of constructing most dialog user interfaces and is the suggested dialog type. <br />ProgressDialog A dialog that displays a progress wheel or progress bar. Because it's an extension of the AlertDialog, it also supports buttons. <br />DatePickerDialog A dialog that allows the user to select a date. See the Hello DatePicker tutorial. TimePickerDialog A dialog that allows the user to select a time.<br />
  190. 190. Creating an AlertDialog<br />An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:<br />A title<br />A text message<br />One, two, or three buttons<br />A list of selectable items (with optional checkboxes or radio buttons)<br />
  191. 191. Creating an AlertDialog & Adding Buttons<br />To create an AlertDialog, use the AlertDialog.Builder subclass. <br />Get a Builder with AlertDialog.Builder(Context) and then use the class's public methods to define all of the AlertDialog properties. After you're done with the Builder, retrieve the AlertDialog object with create().<br />User cannot <br />cancel it by <br />back button<br />
  192. 192. Adding a List<br />
  193. 193. Adding checkboxes and radio buttons<br />No item should <br />be selected by Default<br />
  194. 194. Creating a ProgressDialog<br />A ProgressDialog is an extension of the AlertDialog class that can display a progress animation in the form of a spinning wheel, for a task with progress that's undefined, or a progress bar, for a task that has a defined progression. <br />The dialog can also provide buttons, such as one to cancel a download.<br />Opening a progress dialog can be as simple as calling ProgressDialog.show(). <br />ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", "Loading. Please wait...", true); <br />The first parameter is the application Context, the second is a title for the dialog (left empty), the third is the message, and the last parameter is whether the progress is indeterminate <br />
  195. 195. Showing a progress bar<br />To show the progression with an animated progress bar:<br />Initialize the ProgressDialog with the class constructor, ProgressDialog(Context).<br />Set the progress style to "STYLE_HORIZONTAL" with setProgressStyle(int) and set any other properties, such as the message.<br />When you're ready to show the dialog, call show() or return the ProgressDialog from the onCreateDialog(int) callback.<br />You can increment the amount of progress displayed in the bar by calling either setProgress(int) with a value for the total percentage completed so far or incrementProgressBy(int) with an incremental value to add to the total percentage completed so far.<br />
  196. 196. Lab<br />OK Cancel Dialog with a message<br />List Dialog<br />Progress Dialog<br />Single choice list<br />
  197. 197. User Notification<br />User different technique:<br />A Toast Notification, for brief messages that come from the background.<br />A Status Bar Notification, for persistent reminders that come from the background and request the user's response.<br />A Dialog Notification, for Activity-related notifications.<br />
  198. 198. Creating Toast Notifications<br />A toast notification is a message that pops up on the surface of the window. <br />It only fills the amount of space required for the message and the user's current activity remains visible and interactive. <br />The notification automatically fades in and out, and does not accept interaction events.<br />A toast can be created and displayed from an Activity or Service. If you create a toast notification from a Service, it appears in front of the Activity currently in focus.<br />
  199. 199. Creating Toast Notifications<br />You can also chain your methods and avoid holding on to the Toast object, like this:<br />
  200. 200. Lab<br />Create Toast<br />
  201. 201. Status Bar Notifications<br />
  202. 202. Status Bar Notifications<br />A status bar notification adds an icon to the system's status bar (with an optional ticker-text message) and an expanded message in the "Notifications" window. <br />When the user selects the expanded message, Android fires an Intent that is defined by the notification (usually to launch an Activity). <br />You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.<br />
  203. 203. Status Bar Notifications<br />A status bar notification should be used for any case in which a background Service needs to alert the user about an event that requires a response. <br />A background Service should never launch an Activity on its own in order to receive user interaction. <br />The Service should instead create a status bar notification that will launch the Activity when selected by the user.<br />
  204. 204. Creating Status Bar Notifications<br />Get a reference to the NotificationManager:<br />
  205. 205. Creating Status Bar Notifications<br />Instantiate the Notification:<br />
  206. 206. Creating Status Bar Notifications<br />Define the Notification's expanded message and Intent: <br />
  207. 207. Creating Status Bar Notifications<br />Pass the Notification to the NotificationManager: <br />
  208. 208. Adding Sound, vibration etc<br />notification.defaults |= Notification.DEFAULT_SOUND; <br />notification.defaults |= Notification.DEFAULT_VIBRATE; <br />notification.defaults |= Notification.DEFAULT_LIGHTS; <br />
  209. 209. Lab<br />App->Notification<br />
  210. 210. Adapters<br />Sometimes you'll want to populate a view group with some information that can't be hard-coded, instead, you want to bind your view to an external source of data. <br />To do this, you use an AdapterView as your view group and each child View is initialized and populated with data from the Adapter.<br />
  211. 211. AdapterView<br />Gallery, ListView, and Spinner are examples of AdapterView subclasses that you can use to bind to a specific type of data and display it in a certain way. <br />AdapterView objects have two main responsibilities: <br />Filling the layout with data <br />Handling user selections <br />
  212. 212. SimpleCursorAdapter<br />
  213. 213. SimpleCursorAdapter<br />SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)<br />This adapter converts a<br />row in the cursor to a child view for the container control. The definition of the child view is defined in an XML resource (layout parameter). <br />A row in the cursor might have many columns, you tell the SimpleCursorAdapter which columns you want to select from the row by specifying an array of column names (using the from parameter).<br />Similarly, because each column you select is mapped to a TextView, you must specify the IDs in the to parameter. There’s a one-to-one mapping between the column that you select and a TextView that displays the data in the column, so the from and to parameters must be the same size.<br />
  214. 214. ArrayAdapter<br />ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,new string[]{"sayed","satya"});<br />code creates an ArrayAdapter where the TextView controls’ data is represented by strings.<br />android.R.layout.simple_list_item_1 points to a TextView defined by the Android SDK.<br />
  215. 215. Lab<br />Data for the list comes from an array of strings<br />Data comes from a cursor <br />Data comes from a custom ListAdapter<br />Data comes from a custom ListAdapter and handling user selection<br />
  216. 216. Styles and Themes<br />Perhaps you're not satisfied with the look of the standard widgets. To revise them, you can create some of your own styles and themes.<br />A style is a set of one or more formatting attributes that you can apply as a unit to individual elements in your layout. For example, you could define a style that specifies a certain text size and color, then apply it to only specific View elements.<br />A theme is a set of one or more formatting attributes that you can apply as a unit to all activities in an application, or just a single activity. For example, you could define a theme that sets specific colors for the window frame and the panel background, and sets text sizes and colors for menus. This theme can then be applied to specific activities or the entire application.<br />
  217. 217. Styles and Themes<br />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.<br />Styles in Android share a similar philosophy to cascading stylesheets in web design—they allow you to separate the design from the content.<br />
  218. 218. Style<br />
  219. 219. Defining Style<br />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.<br />The root node of the XML file must be <resources>.<br />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.<br />
  220. 220. Lab<br />Style<br />
  221. 221. APPLICATION MANIFEST<br />
  222. 222. Application Manifest<br />Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. <br />The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the application's code.<br />
  223. 223. Application Manifest<br />The manifest does the following: <br />It names the Java package for the application. The package name serves as a unique identifier for the application.<br />It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched.<br />It determines which processes will host application components.<br />It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.<br />It also declares the permissions that others are required to have in order to interact with the application's components.<br />It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published.<br />It declares the minimum level of the Android API that the application requires.<br />It lists the libraries that the application must be linked against.<br />
  224. 224. Structure of the Manifest File<br />
  225. 225. Elements of Manifest File<br /><action><activity><activity-alias><application><category><data><grant-uri-permission><instrumentation><intent-filter><manifest><meta-data><permission><permission-group><permission-tree><provider><receiver><service><supports-screens><uses-configuration><uses-feature><uses-library><uses-permission><uses-sdk><br />
  226. 226. Manifest Editor<br />Lab<br />
  227. 227. APPLICATION RESOURCES<br />
  228. 228. Application Resources<br />You should always externalize resources such as images and strings from your application code, so that you can maintain them independently. <br />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<br />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.<br />
  229. 229. Application Resources<br />Two different devices, both using default resources<br />Two different devices, one using alternative resources<br />
  230. 230. Providing Resources<br />
  231. 231. Providing Resources<br />
  232. 232. Providing Resources<br />
  233. 233. Providing Resources<br />
  234. 234. Providing Alternative Resources<br />Screen size<br />smallnormallargexlarge<br />Screen aspect<br />longnotlong<br /><ul><li>Screen orientation portland
  235. 235. Screen pixel density (dpi)
  236. 236. ldpimdpihdpixhdpinodpi</li></li></ul><li>Accessing Resources<br />When your application is compiled, aapt generates the R class, which contains resource IDs for all the resources in your res/ directory. <br />Although the R class is where resource IDs are specified, you should never need to look there to discover a resource ID. A resource ID is always composed of:<br />The resource type: Each resource is grouped into a "type," such as string, drawable, and layout. <br />The resource name, which is either: the filename, excluding the extension; or the value in the XML <br />
  237. 237. Accessing Resources<br />There are two ways you can access a resource:<br />In code: Using an static integer from a sub-class of your R class, such as: R.string.hello string is the resource type and hello is the resource name. There are many Android APIs that can access your resources when you provide a resource ID in this format. <br />In XML: Using a special XML syntax that also corresponds to the resource ID defined in your R class, such as: @string/hello string is the resource type and hello is the resource name. You can use this syntax in an XML resource any place where a value is expected that you provide in a resource. <br />
  238. 238. Accessing Resources in Code<br />Here's the syntax to reference a resource in code:<br />[<package_name>.]R.<resource_type>.<resource_name><br /><package_name> is the name of the package in which the resource is located (not required when referencing resources from your own package).<br /><resource_type> is the R subclass for the resource type.<br /><resource_name> is either the resource filename without the extension or the android:name attribute value in the XML element (for simple values).<br />
  239. 239. Use cases<br />
  240. 240. Accessing Resources from XML<br />Here is the syntax to reference a resource in an XML resource:<br />@[<package_name>:]<resource_type>/<resource_name><br /><package_name> is the name of the package in which the resource is located (not required when referencing resources from the same package)<br /><resource_type> is the R subclass for the resource type<br /><resource_name> is either the resource filename without the extension or the android:name attribute value in the XML element (for simple values).<br />
  241. 241. Use Cases<br />
  242. 242. INTENTS<br />
  243. 243. Intents<br />Three of the core components of an application — activities, services, and broadcast receivers — are activated through messages, called intents.<br />Intent messaging is a facility for late run-time binding between components in the same or different applications. <br />The intent itself, an Intent object, is a passive data structure holding an abstract description of an operation to be performed — or, often in the case of broadcasts, a description of something that has happened and is being announced.<br />
  244. 244. Delivering Intents<br />There are separate mechanisms for delivering intents to each type of component: <br />An Intent object is passed to Context.startActivity() or Activity.startActivityForResult() to launch an activity or get an existing activity to do something new. (It can also be passed to Activity.setResult() to return information to the activity that called startActivityForResult().)<br />An Intent object is passed to Context.startService() to initiate a service or deliver new instructions to an ongoing service. Similarly, an intent can be passed to Context.bindService() to establish a connection between the calling component and a target service. It can optionally initiate the service if it's not already running.<br />Intent objects passed to any of the broadcast methods (such as Context.sendBroadcast(), Context.sendOrderedBroadcast(), or Context.sendStickyBroadcast()) are delivered to all interested broadcast receivers. Many kinds of broadcasts originate in system code.<br />
  245. 245. Delivering Intents<br />In each case, the Android system finds the appropriate activity, service, or set of broadcast receivers to respond to the intent, instantiating them if necessary. <br />There is no overlap within these messaging systems: Broadcast intents are delivered only to broadcast receivers, never to activities or services. <br />An intent passed to startActivity() is delivered only to an activity, never to a service or broadcast receiver, and so on. <br />
  246. 246. Intent Objects<br />An Intent object is a bundle of information. <br />It contains information of interest to- <br />the component that receives the intent (such as the action to be taken and the data to act on)<br />information of interest to the Android system (such as the category of component that should handle the intent and instructions on how to launch a target activity). <br />
  247. 247. Intent Objects<br />Principally, Intent Object can contain the following: <br />Component name<br />Action<br />Data<br />Category<br />Extras<br />Flags<br />
  248. 248. Component Name<br />The name of the component that should handle the intent. <br />This field is a ComponentName object — a combination of –<br />the fully qualified class name of the target component (for example "com.example.project.app.FreneticActivity") and<br />the package name set in the manifest file of the application where the component resides (for example, "com.example.project").<br />
  249. 249. Component Name<br />The component name is optional. <br />If it is set, the Intent object is delivered to an instance of the designated class. <br />If it is not set, Android uses other information in the Intent object to locate a suitable target <br />The component name is set by setComponent(), setClass(), or setClassName() and read by getComponent(). <br />
  250. 250. Action<br />A string naming the action to be performed — or, in the case of broadcast intents, the action that took place and is being reported<br />See the Intent class description for a list of pre-defined constants for generic actions.<br />
  251. 251. Action<br />You can also define your own action strings for activating the components in your application. <br />Those you invent should include the application package as a prefix — <br />for example: "com.example.project.SHOW_COLOR". <br />
  252. 252. Action<br />The action largely determines how the rest of the intent is structured — particularly the data and extras fields<br />The action in an Intent object is set by the setAction() method and read by getAction(). <br />
  253. 253. Data<br />The URI of the data to be acted on and the MIME type of that data. <br />Different actions are paired with different kinds of data specifications. For example, <br />if the action field is ACTION_EDIT, the data field would contain the URI of the document to be displayed for editing. <br />If the action is ACTION_CALL, the data field would be a tel: URI with the number to call. <br />if the action is ACTION_VIEW and the data field is an http: URI, the receiving activity would be called upon to download and display whatever data the URI refers to.<br />
  254. 254. Data<br />When matching an intent to a component that is capable of handling the data, it's often important to know the type of data (its MIME type) in addition to its URI. For example, a component able to display image data should not be called upon to play an audio file. <br />The setData() method specifies data only as a URI, setType() specifies it only as a MIME type, and setDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the type by getType().<br />
  255. 255. Category<br />A string containing additional information about the kind of component that should handle the intent. Any number of category descriptions can be placed in an Intent object.<br />See the Intent class description for the full list of categories. <br />
  256. 256. Category<br />The addCategory() method places a category in an Intent object, removeCategory() deletes a category previously added, and getCategories() gets the set of all categories currently in the object. <br />
  257. 257. Extras<br />Key-value pairs for additional information that should be delivered to the component handling the intent. <br />Just as some actions are paired with particular kinds of data URIs, some are paired with particular extras. For example, an ACTION_TIMEZONE_CHANGED intent has a "time-zone" extra that identifies the new time zone, and ACTION_HEADSET_PLUG has a "state" extra indicating whether the headset is now plugged in or unplugged, as well as a "name" extra for the type of headset. <br />If you were to invent a SHOW_COLOR action, the color value would be set in an extra key-value pair. The Intent object has a series of put...() methods for inserting various types of extra data and a similar set of get...() methods for reading the data. <br />the extras can be installed and read as a Bundle using the putExtras() and getExtras() methods. <br />
  258. 258. Flags<br />Flags of various sorts. <br />Many instruct the Android system how to launch an activity (for example, which task the activity should belong to) <br />how to treat it after it's launched (for example, whether it belongs in the list of recent activities). <br />All these flags are defined in the Intent class. <br />
  259. 259. Intent Resolution<br />Intents can be divided into two groups: <br />Explicit intentsdesignate the target component by its name. Since component names would generally not be known to developers of other applications, explicit intents are typically used for application-internal messages — such as an activity starting a subordinate service or launching a sister activity.<br />Android delivers an explicit intent to an instance of the designated target class. Nothing in the Intent object other than the component name matters for determining which component should get the intent. <br />Implicit intentsdo not name a target (the field for the component name is blank). Implicit intents are often used to activate components in other applications.<br />
  260. 260. Implicit Intent Resolution<br />the Android system must find the best component (or components) to handle the intent — <br />a single activity or service to perform the requested action<br />set of broadcast receivers to respond to the broadcast announcement. <br />It does so by comparing the contents of the Intent object to intent filters, structures associated with components that can potentially receive intents. <br />Filters advertise the capabilities of a component and delimit the intents it can handle. <br />They open the component to the possibility of receiving implicit intents of the advertised type. <br />
  261. 261. Implicit Intent Resolution<br />Only three aspects of an Intent object are consulted when the object is tested against an intent filter: <br />action <br />data (both URI and data type) <br />category<br />The extras and flags play no part in resolving which component receives an intent. <br />
  262. 262. Action test<br />To pass this test, the action specified in the Intent object must match one of the actions listed in the filter. <br />If the object or the filter does not specify an action, the results are as follows: <br />If the filter fails to list any actions, there is nothing for an intent to match, so all intents fail the test. No intents can get through the filter.<br />On the other hand, an Intent object that doesn't specify an action automatically passes the test — as long as the filter contains at least one action.<br />
  263. 263. Category test<br />For an intent to pass the category test, every category in the Intent object must match a category in the filter. <br />The filter can list additional categories, but it cannot omit any that are in the intent. <br />In principle, therefore, an Intent object with no categories should always pass this test, regardless of what's in the filter. <br />
  264. 264. Data test<br />Each <data> element can specify a URI and a data type (MIME media type). <br />There are separate attributes — scheme, host, port, and path — for each part of the URI: <br />scheme://host:port/path<br />For example, in the following URI, <br />content://com.example.project:200/folder/subfolder/etc<br />host<br />port<br />scheme<br />path<br />authority<br />
  265. 265. Data test<br />When the URI in an Intent object is compared to a URI specification in a filter, it's compared only to the parts of the URI actually mentioned in the filter. <br />For example-<br />if a filter specifies only a scheme, all URIs with that scheme match the filter. <br />If a filter specifies a scheme and an authority but no path, all URIs with the same scheme and authority match, regardless of their paths. <br />If a filter specifies a scheme, an authority, and a path, only URIs with the same scheme, authority, and path match. However, a path specification in the filter can contain wildcards to require only a partial match of the path. <br />
  266. 266. Data test<br />The type attribute of a <data> element specifies the MIME type of the data. <br />It's more common in filters than a URI. <br />Both the Intent object and the filter can use a "*" wildcard for the subtype field — for example, "text/*" or "audio/*" — indicating any subtype matches. <br />The data test compares both the URI and the data type in the Intent object to a URI and data type specified in the filter. <br />
  267. 267. Data test<br />The rules are as follows: <br />An Intent object that contains neither a URI nor a data type passes the test only if the filter likewise does not specify any URIs or data types.<br />An Intent object that contains a URI but no data type (and a type cannot be inferred from the URI) passes the test only if its URI matches a URI in the filter and the filter likewise does not specify a type. This will be the case only for URIs like mailto: and tel: that do not refer to actual data.<br />An Intent object that contains a data type but not a URI passes the test only if the filter lists the same data type and similarly does not specify a URI.<br />An Intent object that contains both a URI and a data type (or a data type can be inferred from the URI) passes the data type part of the test only if its type matches a type listed in the filter. It passes the URI part of the test either if its URI matches a URI in the filter or if it has a content: or file: URI and the filter does not specify a URI. In other words, a component is presumed to support content: and file: data if its filter lists only a data type.<br />
  268. 268. Lab<br />Create Intents to Launch system activities<br />Browser<br />Phone Dialer<br />Make Phone call<br />
  269. 269. SERVICES<br />
  270. 270. Service Lifetime<br />
  271. 271. Lab<br />Lab<br />
  272. 272. DATA STORAGE<br />
  273. 273. Data Storage<br />Android provides several options for you to save persistent application data. <br />The solution you choose depends on your specific needs, such as whether-<br /> the data should be private to your application or<br />accessible to other applications (and the user) and<br />how much space your data requires. <br />
  274. 274. Data Storage<br />Your data storage options are the following:<br />Shared Preferences Store private primitive data in key-value pairs. <br />Internal Storage Store private data on the device memory. <br />External Storage Store public data on the shared external storage. <br />SQLite Databases Store structured data in a private database. <br />Network Connection Store data on the web with your own network server.<br />
  275. 275. Shared Preferences<br />The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. <br />You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. <br />This data will persist across user sessions (even if your application is killed).<br />
  276. 276. Using Shared Preferences<br />To get a SharedPreferences object for your application, use one of two methods:<br />getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.<br />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.<br />
  277. 277. Using Shared Preferences<br />To write values:<br />Call edit() to get a SharedPreferences.Editor.<br />Add values with methods such as putBoolean() and putString().<br />Commit the new values with commit()<br />To read values, use SharedPreferences methods such as getBoolean() and getString().<br />
  278. 278. Using Shared Preferences<br />Shared Preference <br />file name<br />Get Shared Preference<br />Each getter takes a key and a default value <br />(used when no value has yet been saved <br />for that key)<br />Restore data <br />in your code<br />Read your data<br />Save data<br />
  279. 279. Lab<br />Shared Preferences<br />
  280. 280. Internal Storage<br />You can save files directly on the device's internal storage. <br />By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). <br />When the user uninstalls your application, these files are removed.<br />
  281. 281. Using the Internal Storage<br />To create and write a private file to the internal storage<br />Call openFileOutput() with the name of the file and the operating mode. This returns a FileOutputStream.<br />Write to the file with write().<br />Close the stream with close().<br />
  282. 282. Using the Internal Storage<br />MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application. <br />MODE_APPEND Append to a file<br />MODE_WORLD_READABLE World Readable<br />MODE_WORLD_WRITEABLE World readable/writable<br />
  283. 283. Using the Internal Storage<br />To read a file from internal storage:<br />Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.<br />Read bytes from the file with read().<br />Then close the stream with close().<br />
  284. 284. Lab<br />Internal Storage<br />
  285. 285. Using the External Storage<br />Every Android-compatible device supports a shared "external storage" that you can use to save files. <br />This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. <br />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.<br />
  286. 286. Checking media availability<br />
  287. 287. Accessing files on external storage<br />use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. <br />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). <br />This method will create the appropriate directory if necessary. <br />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). <br />If the user uninstalls your application, this directory and all its contents will be deleted.<br />
  288. 288. Saving files that should be shared<br />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. <br />These directories lay at the root of the external storage, such as Music/, Pictures/, Ringtones/, and others.<br />
  289. 289. Saving files that should be shared<br />Music/ - Media scanner classifies all media found here as user music.<br />Podcasts/ - Media scanner classifies all media found here as a podcast.<br />Ringtones/ - Media scanner classifies all media found here as a ringtone.<br />Alarms/ - Media scanner classifies all media found here as an alarm sound.<br />Notifications/ - Media scanner classifies all media found here as a notification sound.<br />Pictures/ - All photos (excluding those taken with the camera).<br />Movies/ - All movies (excluding those taken with the camcorder).<br />Download/ - Miscellaneous downloads.<br />
  290. 290. Lab<br />External Storage <br />
  291. 291. Using Databases<br />Android provides full support for SQLite databases. <br />Any databases you create will be accessible by name to any class in the application, but not outside the application.<br />
  292. 292. Using Databases<br />
  293. 293. Using Databases<br />You can then get an instance of your SQLiteOpenHelper implementation using the constructor you've defined. <br />To write to and read from the database, call getWritableDatabase() and getReadableDatabase(), respectively. These both return a SQLiteDatabase object that represents the database and provides methods for SQLite operations.<br />You can execute SQLite queries using the SQLiteDatabasequery() methods, which accept various query parameters, such as the table
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×