Introduction to android sessions new


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introduction to android sessions new

  1. 1. Introduction to Android Joe Jacob DEC 2011
  2. 2. Introducing Android•Android is a mobile operating system developed by Google and is based upona modified version of the Linux kernel.•Platform was officially launched on 5th November 2007•Platform is made available by Google under Apache free-software and Opensource License
  3. 3. Introducing Android•Google and the Open Handset Alliance•It was initially developed by Android Inc. (a firm purchased by Google) andlater positioned in the Open Handset Alliance.•The Open Handset Alliance (OHA) is a business alliance of 80 firms fordeveloping open standards for mobile devices. Member firms include Google,HTC, Dell, Intel, Motorola, Qualcomm, Texas Instruments, Samsung, LG, T-Mobile, Nvidia, and Wind River Systems.
  4. 4. Smartphone OS Market Share
  5. 5. Android Releases
  6. 6. Features of Android• Storage – Uses SQLite ,a lightweight relational database for data storage• Connectivity- Supports GSM/EDGE, IDEN, CDMA, EVDO, UMTS ,Bluetooth ,Wi-Fi ,LTE and WiMax• Messaging - Supports both SMS and MMS• Web Browser- Based on the open-source Webkit• Media support - Includes support for H.263 ,H.264,MPEG-4 SP AMR, AMR-WB ,AAC, HE-AAC ,MP3, MIDI, OGG Vorbis WAV,JPEG,PNG,GIF, and BMP
  7. 7. Features of Android• Hardware support – Accelerometer sensor ,Camera, Digital Compass, Proximity Sensor and GPS• Multitouch - Supports multi touch screens• Multitasking-Supports multi tasking applications• Tethering - Supports sharing of Internet connections as a wired /wireless hotspot
  8. 8. Android Architecture
  9. 9. Android Architecture Linux Kernel• Android is built on the Linux kernel.• No native windowing system• Does not include the full set of standard Linux utilities• Patch of “kernel enhancements” to support Android
  10. 10. Android Architecture Libraries• Native libraries are written in C and C++• They provide low level functionality services to the platform• Bionic Libc : Custom libc implementation, optimized for embedded use with small size and fast code paths.• Webkit : Web browser which Renders pages in full (desktop) view. Full CSS, Javascript, DOM, AJAX support.
  11. 11. Android Architecture Libraries• Media Framework : Supports standard video, audio, still-frame formats. Support for hardware / software codec plug-ins. Media support for common audio, video, and still image formats(MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF)• SGL - the underlying 2D graphics engine• 3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software.
  12. 12. Android Architecture Libraries• FreeType - bitmap and vector font rendering• SQLite - a powerful and lightweight relational database engine available to all applications
  13. 13. Hardware Abstraction Libraries• User space C/C++ library layer• Defines the interface that Android requires hardware “drivers” to implement• Separates the Android platform logic from the hardware interface• Why do we need a user-space HAL? • Not all components have standardized kernel driver interfaces • Kernel drivers are GPL which exposes any proprietary IP • Android has specific requirements for hardware drivers
  14. 14. Android Architecture Android Runtime• Dalvik VM and Core Libraries make the runtime.• Every Android application runs in its own process.• Dalvik VM executes files in the Dalvik Executable (.dex) format• Dalvik has a just-in-time compiler (JIT)• Device can run multiple VMs efficiently
  15. 15. Android Architecture Application Framework• Written in Java• Services that are essential to the Android platform• All services are provided for the developers to build application.• It provides access to lower-level hardware APIs
  16. 16. Android Architecture Applications• Applications are written in the Java programming language• 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• Anyone can make a application and integrate it to the platform• Access to all application framework.
  17. 17. Android Devices in the Market Smart phones Tablets E-reader devices Netbooks MP4 players Internet TVs
  18. 18. Android Market• Android Market is an online software store developed by Google for Android OS devices• Its gateway is an application program ("app") called "Market", preinstalled on most Android devices, allows users to browse and download mobile apps published by third-party developers
  19. 19. Tools for Android Development
  20. 20. Setting up Android Development Environment• Start eclipse and select Help->Install New Software
  21. 21. Setting up Android Development Environment• Click Add, in the top-right corner.• In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:•
  22. 22. Setting up Android Development Environment• Check the Developer Tools options and click next
  23. 23. Setting up Android Development Environment• In the next window, youll see a list of the tools to be downloaded. Click Next.
  24. 24. Setting up Android Development Environment• Read and accept the license agreements, then click Finish.
  25. 25. Setting up Android Development Environment• When the installation completes, restart Eclipse.• After youve successfully downloaded the ADT as described above, the next step is to modify your ADT preferences in Eclipse to point to the Android SDK directory
  26. 26. Setting up Android Development Environment• Select Window > Preferences... to open the Preferences panel (Mac OS X: Eclipse > Preferences).• Select Android from the left panel.• For the SDK Location in the main panel, click Browse... and locate your downloaded SDK directory.
  27. 27. Setting up Android Development Environment• Download the Android API version with help of your ADT plug-in.
  28. 28. Setting up Android Development Environment• After the successful installation of Android API next step is to create your Android Virtual Devices (AVDs) to be used for testing your Android applications
  29. 29. Creating Android Virtual Devices• To create an AVD go to windows -> Android SDK and AVD Manager• Click virtual Devices item in the left pane of the window. Then click New – Type Name – Select Target API – Specify SD card Size and click create button
  30. 30. Creating Android Virtual Devices• After the creation of virtual device you can start your AVD from Android SDK and AVD Manager
  31. 31. Creating Your First Android Application
  32. 32. Hello World Application• Using Eclipse ,create a new project by selecting File->Project->Android->Android Project
  33. 33. Hello World Application• Name the Android project ,Select Build Target and Fill the Properties, then click finish
  34. 34. Hello World Application
  35. 35. Structure of an Android Application• Various folders and their files are:
  36. 36. Structure of an Android Application
  37. 37. Running your Application• Select the project name in Eclipse and press F11. You will be asked to select a way to debug the application. Select Android Application as shown
  38. 38. Running your Application• The Android Emulator (AVD) will start and application will be installed in the device and begin to run.
  39. 39. Building Blocks of an Android Application
  40. 40. Android Architecture Application Building Blocks
  41. 41. Android Architecture Application Building Blocks
  42. 42. Activity• An activity is a single, focused thing that the user can do.• An activity provides a user interface for a single screen in your application• A concrete class in the API• They run in the process of the .APK which installed them• Each activity is responsible for saving its own state so that it can be restored later as part of the application life cycle.
  43. 43. Activity Lifecycle • Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activitys previously frozen state, if there was one. • Called after your activity has been stopped, prior to it being started again. • Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden. • Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. • Always followed by onPause(). • when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU‫ز‬Implementation of this method must be very quick because the next activity will not be resumed until this method returns. • Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. • The final call you receive before your activity is destroyed
  44. 44. Activity LifetimeThere are three key loops you may be interested in monitoring within your activity:• The entire lifetime of an activity happens between the first call to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do all setup of "global" state in onCreate(), and release all remaining resources in onDestroy(). For example, if it has a thread running in the background to download data from the network, it may create that thread in onCreate() and then stop the thread in onDestroy().
  45. 45. Activity Lifetime• The visible lifetime of an activity happens between a call to onStart() until a corresponding call to onStop(). During this time the user can see the activity on- screen, though it may not be in the foreground and interacting with the user. Between these two methods you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onStart() to monitor for changes that impact your UI, and unregister it in onStop() when the user an no longer see what you are displaying. The onStart() and onStop() methods can be called multiple times, as the activity becomes visible and hidden to the user.
  46. 46. Activity Lifetime• The foreground lifetime of an activity happens between a call to onResume() until a corresponding call to onPause(). During this time the activity is in front of all other activities and interacting with the user.• An activity can frequently go between the resumed and paused states• Example when the device goes to sleep, when an activity result is delivered, when a new intent is delivered -- so the code in these methods should be fairly lightweight.
  47. 47. Process LifecycleProcess • Android process == Linux process (w/ its own unique UID) • A process has one main thread which is also named the UI thread which lives as long as the process lives. A process can also have more threads which are useful for background tasks. A process starts when the user launches your application, assuming that it is not running already in the background. • The process end is less determinant. It will happen sometime after the user or system has closed all the activities. If for example you have one activity and the user pressed on the back key, the activity gets closed. Later when the phone gets low on memory (and eventually it will happen) the process will quit. .
  48. 48. Process LifecycleProcess The Android system attempts to keep application process around for as long as possible, but eventually will need to remove old processes when memory runs low.In general, there are four states a process can be in based on the activities running in it, listed here in order of importance. The system will kill less important processes (the last ones) before it resorts to killing more important processes (the first ones).The foreground activity (the activity at the top of the screen that the user is currently interacting with) is considered the most important. Its process will only be killed as a last resort, if it uses more memory than is available on the device. Generally at this point the device has reached a memory paging state, so this is required in order to keep the user interface responsive.A visible activity (an activity that is visible to the user but not in the foreground, such as one sitting behind a foreground dialog) is considered extremely important and will not be killed unless that is required to keep the foreground activity running. • .
  49. 49. Process LifecycleProcess• A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it.• An empty process is one hosting no activities or other application components (such as Service or BroadcastReceiver classes). These are killed very quickly by the system as memory becomes low. For this reason, any background operation you do outside of an activity must be executed in the context of an activity BroadcastReceiver or Service to ensure that the system knows it needs to keep your process around. .
  50. 50. IntentsIntent• An intent generically defines an “intention” to do some work. Intents encapsulate several concepts. You can use intents to perform the following tasks, for instance: . • Launch an activity • Start a service • Dial a phone number or answer a phone call • Display a web page or a list of contacts • Broadcast a message
  51. 51. IntentsIntent• An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, . where it can be thought of as the glue between activities.• It is basically a passive data structure holding an abstract description of an action to be performed. The primary pieces of information in an intent are:•action -- The general action to be performed, such as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.•data -- The data to operate on, such as a person record in the contacts database, expressed as a Uri.
  52. 52. ServicesServices Service is an application component that can perform long-running operations in . the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
  53. 53. ServicesServicesA service can essentially take two forms:StartedA service is "started" when an application component (such as an activity) starts it by calling . startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.BoundA service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
  54. 54. Permissions• Global access to a service can be enforced when it is declared in its manifests <service> tag. Other applications will need to declare a corresponding <uses- permission> element in their own manifest.• A service can protect individual IPC calls into it with permissions, by calling the checkCallingPermission(String) method before executing the implementation of that call.
  55. 55. ServicesServices Lifetime .
  56. 56. The Application’s ManifestEvery application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest presents essential information about the application to the Android system, information the system must have before it can run any of the applications code.•Declares the permissions the application will need (uses-permission)•Declare. permissions that activities or services might require to use yourapp (permission)•Provides instrumentations elements (instrumentation)•Provides hooks to connect to optional Android components such asmapping (uses-library )
  57. 57. The Default Application’s Manifest• One application node. Application properties include icon and application label in home screen.• One Activity node. Activity name is abbreviated to .Sample. Tells Android which Java class to load. The activity label is the title for that activity in the titlebar.• . Intent-filter tags specify which Intents launch the Activity. In order for an application to be available from the launcher it must include an Intent Filter listening for the MAIN action and the LAUNCHER category.<manifest xmlns:android- package=“com.motorola.Sample”> <application android:icon="@drawable/icon“ android:label="@string/app_name"> <activity android:name=".Sample" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
  58. 58. Content Providers•Makes a specific set of application data available to other application .•Examples •◦Data stored in filesystem •◦Data stored in SQLite db•Implement a set of methods to retrieve and store data•A ContentResolver is used to call the methods in a content provider
  59. 59. Content Providers• Content providers are one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only required if you need to share data between multiple applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. If you dont need to share data amongst multiple applications you can use a database directly via SQLiteDatabase.• Android ships with a number of content providers for common data types (audio, video, images, personal contact information, and so on). You can see some of them listed in the android.provider package.• If you want to make your own data public, you have two options: You can create your own content provider (a ContentProvider subclass) or you can add the data to an existing provider.
  60. 60. Making the query• Use either the ContentResolver.query() method or the Activity.managedQuery() method and both return a Cursor object.• managedQuery() causes the activity to manage the life cycle of the Cursor. A managed Cursor handles all of the niceties, such as unloading itself when the activity pauses, and requerying itself when the activity restarts.
  61. 61. Making the query- Using Android Provider
  62. 62. What the above query returns
  63. 63. Reading retrieved data
  64. 64. Modifying Data
  65. 65. Creating a Content Provider• Carefully document the data type of each column. Clients need this information to read the data.• Define a ContentProvider subclass and implement six abstract methods declared in the ContentProvider class. – query() -which returns data to the caller. insert() -which inserts new data into the content provider. update() -which updates existing data in the content provider. delete() which deletes data from the content provider. getType() -which returns the MIME type of data in the content provider onCreate()-which is called to initialize the provider.
  66. 66. Broadcast Receivers• A broadcast receiver is a component that does nothing but receive and react to broadcast announcements.• Many broadcasts originate in system code — for example, announcements that the time zone has changed, that the battery is low, that a picture has been taken, or that the user changed a language preference. Applications can also initiate broadcasts — for example, to let other applications know that some data has been downloaded to the device and is available for them to use.• All receivers extend the BroadcastReceiver base class.
  67. 67. Broadcast Receivers•Receive and react to broadcasts .•Many originate in system code •Low battery •Picture has been taken •Change in timezone •Change in language•Do not have a user interface•Can start an activity that interacts with the user
  68. 68. Broadcast Receiver Lifecycle• A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent).• Don’t show a dialog or bind to a service from within a BroadcastReceiver. Use the NotificationManager API or Context.startService() instead .
  69. 69. Types of Broadcasts• Normal broadcasts- (sent with Context.sendBroadcast) are completely asynchronous. All receivers of the broadcast are run in an undefined order.• Ordered broadcasts-(sent with Context.sendOrderedBroadcast) are delivered to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it wont be passed to other receivers.
  70. 70. Permissions• Access permissions can be enforced by either the sender or receiver of an Intent. – By Sender • Supply a non-null permission argument to sendBroadcast(Intent, String) or sendOrderedBroadcast(Intent, String, BroadcastReceiver, android.os.Handler, int, String, Bundle) • Only receivers who have been granted this permission (by requesting it with the <uses-permission> tag in their AndroidManifest.xml) will be able to receive the broadcast.
  71. 71. Permissions• By Receiver • Supply a non-null permission when registering your receiver -- either when calling registerReceiver(BroadcastReceiver, IntentFilter, String, android.os.Handler) or in the static <receiver> tag in your AndroidManifest.xml. • Only broadcasters who have been granted this permission (by requesting it with the <uses-permission> tag in their AndroidManifest.xml) will be able to send an Intent to the receiver.
  72. 72. User Interface • 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. • View objects are the basic units of user interface expression on the Android platform. The View class serves as the base for subclasses called "widgets," which offer fully implemented UI objects, like text fields and buttons. • ViewGroup class serves as the base for subclasses called "layouts," which offer different kinds of layout architecture, like linear, tabular and relative
  73. 73. Creating Menus• Menus are an important part of any application. They provide familiar interfaces that reveal application functions and settings. Android offers an easy programming interface for developers to provide standardized application menus for various situations.• Android offers two fundamental types of application menus: – Options Menu – Context Menu
  74. 74. Options Menu• This is the primary set of menu items for an Activity. It is revealed by pressing the device MENU key. Within the Options Menu are two groups of menu items: – Icon Menu • This is the collection of items initially visible at the bottom of the screen at the press of the MENU key. It supports a maximum of six menu items. These are the only menu items that support icons and the only menuitems that do not support checkboxes or radio buttons. – Expanded Menu • This is a vertical list of items exposed by the "More" menu item from the Icon Menu. It exists only when the Icon Menu becomes over-loaded and is comprised of the sixth Option Menu item and the rest.
  75. 75. Options Menu/* Creates the menu items */public boolean onCreateOptionsMenu(Menu menu) {menu.add(0, MENU_NEW_GAME, 0, "New Game");menu.add(0, MENU_QUIT, 0, "Quit");return true;}/* Handles item selections */public boolean onOptionsItemSelected(MenuItem item) {switch (item.getItemId()) {case MENU_NEW_GAME:newGame();return true;case MENU_QUIT:quit();return true;}return false;}
  76. 76. Context Menu • This is a floating list of menu items that may appear when you perform a long-press on a View (such as a list item).public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {super.onCreateContextMenu(menu, v, menuInfo);menu.add(0, EDIT_ID, 0, "Edit");menu.add(0, DELETE_ID, 0, "Delete");}public boolean onContextItemSelected(MenuItem item) {AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();switch (item.getItemId()) {case EDIT_ID:editNote(;return true;case DELETE_ID:deleteNote(;return true;default:return super.onContextItemSelected(item);}})
  77. 77. Submenus• A sub menu can be added within any menu, except another sub menu. These are very useful when your application has a lot of functions that may be organized in topics, like the items in a PC applications menu bar (File, Edit, View etc.).• A sub menu is created by adding it to an existing Menu with addSubMenu(). This returns a SubMenu object (an extension of Menu). You can then add additional items to this menu, with the normal routine, using the add() methods
  78. 78. SubMenupublic boolean onCreateOptionsMenu(Menu menu) {boolean result = super.onCreateOptionsMenu(menu);SubMenu fileMenu = menu.addSubMenu("File");SubMenu editMenu = menu.addSubMenu("Edit");fileMenu.add("new");fileMenu.add("open");fileMenu.add("save");editMenu.add("undo");editMenu.add("redo");return result;}