157
Android Applications Development Getting started on the Android Platform March 12 – 14, 2014 Prepared By Michael Angelo M. Rivera Deuphil B. Kaufmann

Android Applications Development (a Walkthrough)

Embed Size (px)

DESCRIPTION

Slides that I and Michael Angelo Rivera created for an Android Development Training workshop we conducted internally. Future revisions will be done based on feedbacks.

Citation preview

  • 1. Android Applications Development Getting started on the Android Platform March 12 14, 2014 Prepared By Michael Angelo M. Rivera Deuphil B. Kaufmann
  • 2. Agenda Whats the Android platform ? Version History. Android and beyond (Future) All about the Android Architecture Tools and SDK overview. Hello Android Walkthrough Android User Interface.
  • 3. Agenda Activities & Intents Working with Services BroadcastReceiver SQLite and ContentProvider SharedPreferences Connecting to the Internet The Android Manifest
  • 4. Android OS based on the Linux kernel & designed primarily for touchscreen mobile devices such as smartphones & tablet computers. Initially developed by Android, Inc., which Google backed financially & later bought in 2005, It was unveiled in 2007 along with the founding of the Open Handset Alliancea consortium of hardware, software, & telecom companies devoted to advancing open standards for mobile devices.
  • 5. Android provides a rich application framework that allows you to build innovative apps and games for mobile devices in a Java language environment. powers hundreds of millions of mobile devices in more than 190 countries around the world.
  • 6. Android The first publicly available smartphone running Android, the HTC Dream (G1), was released on October 22, 2008
  • 7. Android As of September 2013, one billion Android devices have been activated
  • 8. History Android Versions
  • 9. History Android Versions Android 1.5, Cupcake Introduced: April 30, 2009 Key features in this version of Android: Integration of home screen widgets, support for folders on home screen, stereo Bluetooth support, copy/paste in web browser, video recording and playback. Notable devices of the day: HTC Hero, T- Mobile G1, T-Mobile Cliq, Samsung Moment, LG Eve, Motorola Backflip
  • 10. History Android Versions Android 1.6, Donut Introduced: September 15, 2009 Key features in this version of Android: Quick search box, updated interface for camera, camcorder, and gallery, updated Google Play (Android Market), battery usage indicator, text-to-speech engine, Notable devices of the day: LG Optimus, Motorola Devour, Samsung Behold II, Samsung Galaxy, Sony Ericsson Xperia X10, Garminfone.
  • 11. History Android Versions Android 2.0 2.1 Eclair Introduced: October 26, 2009 Key features in this version of Android: Google Maps Navigator (beta), updated browser, support for multiple accounts, improved keyboard, SMS search, Exchange support. Notable devices of the day: Motorola Droid, Motorola Charm, Motorola Flipout, Samsung Galaxy S, Acer Liquid E, HTC Desire.
  • 12. History Android Versions Android 2.2 2.3 Froyo Introduced: May 20, 2010 Key features in this version of Android: Support for Adobe Flash, portable hotspots, multiple keyboard languages, speed and performance improvements, enhanced Microsoft Exchange support. Notable devices of the day: Nexus One, HTC EVO, Droid Incredible, Droid X, Samsung Droid Charge, Sidekick 4G.
  • 13. History Android Versions Android 2.3 2.3.7 Gingerbread Introduced: December 6, 2010 Key features in this version of Android: UI refinements, NFC support, native support for SIP VOIP, faster/more intuitive text input, enhanced copy and paste. Notable devices of the day: Nexus S, HTC Sensation, HTC EVO 3D, Motorola Droid Razr, Samsung Galaxy S II, Sony Xperia Play
  • 14. History Android Versions Android 3.0 3.2 Honeycomb Introduced: February 22, 2011 Key features in this version of Android: Revamped (holographic) UI designed specifically for tablets, action bar, improved multi-tasking, updated standard Android apps, better copy/paste, redesigned keyboard. Notable devices of the day: Motorola Xoom, Eee Pad Transformer, Samsung Galaxy Tab.
  • 15. History Android Versions Android 4.0 Ice Cream Sandwich Introduced: October 19, 2011 Key features in this version of Android: improved multi-tasking, face unlock, resizeable widgets, Android beam, enhanced email options, improved text and voice input, soft buttons can replace hard keys. Notable devices of the day: Galaxy Nexus, HTC One X, LG Optimus G, Samsung Galaxy Note 10.1, Motorola Droid Razr M, Sony Xperia T.
  • 16. History Android Versions Android 4.1 4.3 Jelly Bean Introduced: July 9, 2012 Key features in this version of Android: larger, rich, and actionable notifications, Google Now, offline voice dictation, streamlined UI, performance improvements Project Butter, smart widget placement, multi-user profiles for tablets (4.2), lock screen widgets (4.2), daydream (4.2), OpenGL ES 3.0 (4.3), Bluetooth Smart Ready (4.3), restricted user profiles for tablets (4.3). Notable devices of the day: Samsung Galaxy S3, Samsung Galaxy S4, Samsung Galaxy Note 3, Motorola Moto X, LG G2, Sony Xperia Z, HTC One, Motorola Droid Razr Ultra.
  • 17. Android and beyond
  • 18. Android and beyond Android 4.4 4.4.2, KitKat Introduced: October 23, 2013 Key features in this version of Android: Host Card Emulation,Printing framework,Storage access framework,Low-power sensors,SMS provider,Full-screen Immersive mode,Transitions framework,Chromium WebView,Screen recording,RenderScript NDK,Bluetooth HOGP and MAP,IR Blasters,Closed captioning settings,RTL features,Security enhancements ,Tools for analyzing memory use.
  • 19. Android and beyond
  • 20. Android and beyond
  • 21. Android and beyond Host Card Emulation (HCE) introduces new platform support for secure NFC-based transactions through Host Card Emulation (HCE), for payments, loyalty programs, card access, transit passes, and other custom services. With HCE, any app on an Android device can emulate an NFC smart card, letting users tap to initiate transactions with an app of their choice
  • 22. Android and beyond IR Blasters you can build apps that let users remotely control nearby TVs, tuners, switches, and other electronic devices. The API lets your app check whether the phone or tablet has an infrared emitter, query it's carrier frequencies, and then send infrared signals.
  • 23. Android and beyond Wearables
  • 24. Android and beyond The Open Automotive Alliance- is a global alliance of technology and auto industry leaders committed to bringing the Android platform to cars starting in 2014.
  • 25. Android Architecture
  • 26. Android Architecture Linux Kernel Relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack and driver model. The kernel also acts as an abstraction layer between the hardware and the rest of the software stack.
  • 27. Android Architecture Dalvik Virtual Machine It is a type of JVM used in android devices to run apps and is optimized for low processing power and low memory environments. Unlike the JVM, the DVM doesnt run .class files, instead it runs .dex files. .dex files are built from .class file at the time of compilation and provides higher efficiency in low resource environments. The Dalvik VM allows multiple instance of Virtual machine to be created simultaneously providing security, isolation, memory management and threading support. It is developed by Dan Bornstein of Google.
  • 28. Android Architecture Core Java Libraries These are different from Java SE and Java ME libraries. However these libraries provides most of the functionalities defined in the Java SE libraries.
  • 29. Android Architecture A bit more explanation Java source code is still compiled into .class les. But after .class les are generated, the dx tool is used to convert the .class les into a .dex, or Dalvik Executable, le. Whereas a .class le contains only one class, a .dex le contains multiple classes. It is the .dex le that is executed on the Dalvik VM.
  • 30. Android Architecture Libraries Androids native libraries. It is this layer that enables the device to handle different types of data. These libraries are written in c or c++ language and are specific for a particular hardware.
  • 31. Android Architecture Application Framework These are the blocks that our applications directly interacts with. These programs manage the basic functions of phone like resource, activity, &voice call management etc. As a developer, you just consider that these are some basic tools with which we are building our applications. Written in Java.
  • 32. Android Architecture Applications the top layer in the Android architecture and this is where our applications are going to fit. Several standard applications comes pre-installed with every device, such as: SMS client app, Dialer, Web browser & Contact manager. As a developer we are able to write an app which replace any existing system app. That is, you are not limited in accessing any particular feature. You are practically limitless and can whatever you want to do with the android (as long as the users of your app permits it). Thus Android is opening endless opportunities to the developer
  • 33. Tools and SDK
  • 34. Tools and SDK Overview Software Requirements Java Development Kit (JDK), at least JDK 6 http://goo.gl/kCLldE Eclipse IDE, at least 3.6.2 (Helios) 32-bit - http://goo.gl/RD3wUh 64-bit - http://goo.gl/11uQDQ ADT Eclipse plug-in Update Site - https://dl-ssl.google.com/android/eclipse/ Offline - http://goo.gl/BsyGQ1 Android SDK http://goo.gl/3b0oNG
  • 35. Tools and SDK Overview Setting up Install JDK Install Eclipse Install ADT (via Update Site or offline package) Extract the Android SDK to desired install location Note: Make sure you have the necessary access rights to the install location Set Android SDK path in Eclipse under Window > Preferences > Android > SDK Location, and select OK Optional: Add to path to environment, ex. ANDROID_HOME
  • 36. Tools and SDK Overview Android SDK AVD Manager For managing Emulators SDK Manager For managing Android Runtimes/Libraries tools/ DDMS (ddms.bat) For monitoring devices for debugging 9-Patch Tool (draw9patch.bat) LINT (lint.bat) Hierarchy Viewer (hierarchyview.bat) platform-tools Android Device Bridge (adb.exe) Logcat (adb logcat) For getting system logs
  • 37. Tools and SDK Overview IDEs Eclipse Android ADT Bundle (Eclipse-based) IntelliJ AndroidStudio Build/CI Tools Ant Maven Gradle Jenkins/Hudson TravisCI Testing Android Instruments (with JUnit) Robolectric Robotium
  • 38. Hello Android Walkthrough
  • 39. Android UI and Resources
  • 40. Densities and Sizes (*cough* fragmentation)
  • 41. Sizes Actual physical size, measured as the screen's diagonal There are four generalized sizes: small, normal, large, xlarge
  • 42. Densities The quantity of pixels within a physical area of the screen Core densities: low (ldpi), medium (mdpi), high (hdpi), extra high (xhdpi) (, and xxhdpi)
  • 43. Densities BAD! GOOD!
  • 44. Android Metrics Density-independent Pixels (dip/dp) Screen density independent metric equivalent to 160 dpi dp = px / (dpi / 160) Used for View and ViewGroups dimensions Scale-indepedent Pixels (sp) Similar to dp, but dependent on user font size preferences Used for text size Fixed System Attributes WRAP_CONTENT FILL_PARENT (deprecated and renamed MATCH_PARENT in API Level 8 and higher) Pixels (px), Points (pt), (Millimeters) mm, (Inches) in Dont you use them even if your life depends on it
  • 45. Building Options Programmatically (Runtime; Swing-like) Using XML Layouts (Compiled; Recommended way)
  • 46. Views The basic building block for UI components Occupies a rectangular area on the screen and is responsible for drawing and event handling Get a reference via findViewById(resourceId:int) Key Views TextView EditText Button ImageButton ImageView RadioButton CheckBox Spinner ProgressBar ListView
  • 47. Views TextView Displays text to the user Key Methods set-/getText setTextStyle setTextSize setTextColor
  • 48. Views EditText Inherits from TextView On top of TextView, it allows it to be editable Key Methods Same as TextView
  • 49. Views Button Represents a push- button Key Methods/Events set-/getText setTextSize setTextStyle setEnabled View.onClickListener
  • 50. Views ImageButton Same as button, but focused on an image rather on texts Not a subclass of Button Key Methods/Events setImageResource setImageDrawable setEnabled View.OnClickListener
  • 51. Views ImageView Container for images No GIFs Key Methods/Events setImageResource setImageDrawable
  • 52. Views CheckBox Represents a 2-state button, as checked and unchecked only A subclass of CompoundButton Key Methods/Events isChecked setChecked toggle View.OnClickListener
  • 53. Views RadioButton Represents a 2-state button, as selected and unselected only A subclass of CompoundButton For mutual exclusive selection, must be wrapped around a RadioGroup Key Methods/Events Same as CheckBox
  • 54. Views ProgressBar Presents a visual indicator of progress in some operation Progress can be set incrementally or be set a indeterminate Key Methods/Events setProgress setMax setIndeterminate
  • 55. Views Spinner Represents a collapsed dropdown menu of selection Populate data with an Adapter Key Methods/Events AdapterView.OnItemS elected setAdapter
  • 56. Views ListView Widget for displaying lists Populate data with an Adapter Key Methods/Events AdapterView.OnItemC lick AdapterView.OnItemL ongClick setAdapter
  • 57. Adapters Bridges the AdapterView (ListView, Spinners etc.)to an underlying data In charge of creating and managing list item Views Key/Common Adapter Classes ArrayAdapter BaseAdapter CursorAdapter SimpleCursorAdapter
  • 58. Adapters - ArrayAdapter A concrete implementation of BaseAdapter backed by an array of objects Usage Options Create an instance directly from an Array-resource via a static method Create an instance with custom Objects via its constructors
  • 59. Adapters - BaseAdapter Base class for most Adapter implementations A good practice is to extend this class rather than relying on ArrayAdapter This allows your code to be maintained easier as it grows and requirements changes The implementer doesnt have to worry how its made as its encapsulated away Used with the infamous workaround ViewHolder- pattern for optimizing View creations You may also create a custom View instead of a ViewHolder
  • 60. ViewGroups A special View that serves as an invisible container to other Views/ViewGroups Base class for all layouts Includes an implementation of ViewGroup.LayoutParams, which defines the attributes that affects containing children Views Key ViewGroups LinearLayout RelativeLayout FrameLayout ScrollLayout
  • 61. ViewGroup LinearLayout Is a ViewGroup that aligns all its children Views into a single direction, either vertically or horizontally Options are LinearLayout.HORIZONTAL and LinearLayout.VERTICAL, default is horizontal setOrientation-method (programmatically) android:orientation-attribute (xml) Supports assigning of weights or importance to its children setWeigtSum (programmatically); This sets the total weight that can be distributed android:weightSum-attribute (xml) android:layout_weight-attribute (xml); This sets the weight of the child View in relation to its parent
  • 62. ViewGroup RelativeLayout Is a ViewGroup that displays its child views in relative positions Can position Views, relative to its parent (the RelativeLayout) or to its neighbouring Views Reference to other Views is via an assumed resource ID Sample Attributes android:layout_below=@+id/someViewAbove android:layout_centerInParent=true android:layout_alignParentBottom=true
  • 63. ViewGroup FrameLayout Is a ViewGroup that displays single Views on a screen Child positions can be changed with gravity Child views are drawn in a stack, last items are drawn on top (think z-index) The size of the FrameLayout is based on the largest child View
  • 64. ViewGroup ScrollView Is a ViewGroup that wraps its content in a scrollable container Only 1 child View per ScrollView Is a subclass of FrameLayout Never use a ListView with a ScrollView Scroll-events will collide The ListView will create a view for every item, defeating the purpose and will cause performance degradation Its just plain wrong!
  • 65. OptionsMenu Represents a menu of common actions on a screen (ex. Help, Settings, etc.) Pre-Honeycomb (Android 3.0) accessible via hardware menu button Honeycomb to present will present the menu in the ActionBar Menu items are defined under the menu sub- resource in XML (recommended) Called Actions on Honeycomb and above
  • 66. ContextMenu Represents a menu that is contextually created, usually on a ListView (ex. Delete, Share, etc.) Two implementation alternatives Floating ContextMenu ActionMode* Same with OptionsMenu, must be defined in the menu sub-resource in XML Usually triggered via a long item click in a ListView (ex. Long-Hold-To-Delete)
  • 67. Toasts Provides a small and simple popup to feedback about an operation Provides only 2 popup durations TOAST_SHORT about 3 seconds TOAST_LONG about 5 seconds
  • 68. Dialogs A small window that prompts the user to make a decision or enter additional information Does not fill the screen and is normally used for modal events that require users to take an action before they can proceed Cannot exist without a parent Window/Activity Must ensure to dismiss/de-reference to avoid leaks Key Classes AlertDialog AlertDialog.Builder ProgressDialog (avoid!) TimePickerDialog DatePickerDialog
  • 69. AlertDialogs(.Builder) A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout Provides 3 button options, a positive, a negative, and a neutral one Creation is through AlertDialog.Builder
  • 70. Date-/TimePickerDialog Provides controls for selecting each part of the time (hour, minute, AM/PM) or date (month, day, year) Helps ensure that your users can pick a time or date that is valid, formatted correctly, and adjusted to the user's locale Creation is through a constructor
  • 71. Resources Are external application artifacts and configurations of an Android App Provides a system to adjust and align with different device configuration, such as localizations, strings, images, UIs, and animations There are two basic scenarios A developer will specify default resources that will be used by the platform regardless of device configuration Example: An animation resource that is common to all device configuration Or, a developer will specify multiple resources depending on a target set of device configurations Example: String resources that are for both English and Spanish users or layout resources that has one for portrait and another one for landscape
  • 72. Resources Resources reside under the /res-folder of your project directory Every resource will have its own ID under its namespace (Ex. R.string.hello_worldThe R.java class contains all the generated IDs and only the SDK is able to generate Usage Examples In XML @:/ Ex. android:textColor=@android:color/transparent Programmatically (Runtime) .R.. Ex. editText.setText(R.string.hello_world)
  • 73. Resources Key Resource Types Animation (tweens or frame animations) Drawable (images PNG (and/or JPG)) Colors (HEX colors) Layout or UIs (your XML UI layouts) Menus (your OptionsMenu or ContextMenu resources) String (external texts and/or text localizations) Arrays (external arrays, such as Email Types) Arrays (text arrays, such as Email Types) Dimensions (pixels, points, inches, millimetres) Other Resource Types Style (UI and/or component themes) String Plurals (texts for defining plurality, such as Elf and Elves) Color State Lists, Booleans, Integers, IDs, TypedArray
  • 74. Resources Qualifiers Device Density (Ex. hdpi, xhdpi, mdpi) Device Size (Ex. normal, large) Country Code/MCC (Ex. mcc630) Network Code/MNC (Ex. Mnc610) Language (Ex. En, Es) Region (Ex. rUS, rES) Layout Direction (Ex. LTR, RTL) Orientation (Ex. Portrait, landscape) Version (Ex. v14, v7) Others are Smallest Screen Width, Screen Widht, Screen Height, Ratio, UI Mode, Night Mode, Touch Screen, Keyboard, Text Input, Navigation State, Navigation Method, Dimension
  • 75. Drawable Resources A drawable resource is a general concept for a graphic that can be drawn to the screen Resource Reference In XML: @drawable/ In Java: R.drawable. Drawable Resource Types Bitmap (.PNG, .JPG, or .GIF) Shape (geometric shapes) Nine-Patch (stretchable images, .9.PNG) Layer List (a stack/array of drawables) State List (multi-state drawables; Ex. On-Off Image) Level List (alternative drawables depending on value) Transition (crossfaded drawables) Others are Inset, Scale, and Clip
  • 76. String Resources Provides text strings for your application with optional text styling and formatting Resource Reference In XML: @string/ In Java: R.string. Types String (normal text, can be formatted) String Arrays (for text arrays) Quantity String/Plurals (texts for pluralizations) Basic HTML formatting are supported (, , , etc.)
  • 77. Layout Resources Defines the architecture for the UI in an Activity or a component of a UI Resource Reference for Layout XMLs In XML: @layout/ In Java: R.layout. Resource Reference for individual Views/ViewGroups In XML: @id/ In Java: R.id. Considerations when using RelativeLayouts Preceding Views can be referenced directly Ex. android:layout_below=@id/preceedingViewId Succeeding Views must be referenced with the assumption it is still not created Ex. android:layout_above=@+id/succeedingViewId
  • 78. Activities and IntentFilters
  • 79. Activities Provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. The window typically fills the screen, but may be smaller than the screen and float on top of other windows. An application usually consists of multiple activities that are loosely bound to each other. To create an activity, you must create a subclass ofActivity(or an existing subclass of it).
  • 80. Activities There are two methods almost all subclasses of Activity will implement: onCreate(Bundle) - where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically. onPause() - is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).
  • 81. Activities Lifecycle An activity has essentially four states: If an activity in the foreground of the screen (at the top of the stack), it is active or running. If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations.
  • 82. Activities Lifecycle An activity has essentially four states: If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere. If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.
  • 83. Activities Lifecycle
  • 84. Activities Tasks & Backstack A representation of how each new activity in a task adds an item to the back stack. When the user presses the Back button, the current activity is destroyed and the previous activity resumes.
  • 85. Activities Tasks & Backstack Task is a collection of activities that users interact with when performing a certain job. is a cohesive unit that can move to the "background" when users begin a new task or go to the Home screen, via the Homebutton. While in the background, all the activities in the task are stopped, but the back stack for the task remains intactthe task has simply lost focus while another task takes place. can then return to the "foreground" so users can pick up where they left off.
  • 86. Activities Tasks & Backstack Two tasks: Task B receives user interaction in the foreground, while Task A is in the background, waiting to be resumed.
  • 87. Activities Starting You can start another activity by calling startActivity(), passing it an Intent that describes the activity you want to start. The intent specifies either the exact activity you want to start or 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). An intent can also carry small amounts of data to be used by the activity that is started.
  • 88. Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); Explicit Intent Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent); Implicit Intent Activities Starting
  • 89. Activity for a result Activities Starting start the activity by calling startActivityForResult() (instead of startActivity()). To then receive the result from the subsequent activity, implement the onActivityResult() callback method. When the subsequent activity is done, it returns a result in an Intent to your onActivityResult() method.
  • 90. Activities - Starting static final int PICK_CONTACT_REQUEST = 1; // The request code ... private void pickContact() { Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts")); pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST); } The integer argument is a "request code" that identifies your request. When you receive the result Intent, the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
  • 91. Activities - Starting @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Check which request we're responding to if (requestCode == PICK_CONTACT_REQUEST) { // Make sure the request was successful if (resultCode == RESULT_OK) { // The user picked a contact. // The Intent's data Uri identifies which contact was selected. // Do something with the contact here (bigger example below) } } }
  • 92. Intents is a messaging object you can use to request an action from another app component. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. created with an Intent object, which defines a message to activate either a specific component or a specific type of componentan intent can be either explicit or implicit, respectively.
  • 93. Intents Two types Explicit - specify the component to start by name (the fully-qualified class name). You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. Implicit - do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it.
  • 94. Intents Two types When you create an explicit intent to start an activity or service, the system immediately starts the app component specified in the Intent object. When you create an implicit intent, the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device.
  • 95. Intents Implicit Intent [1]Activity Acreates anIntentwith an action description and passes it tostartActivity().[2]The Android System searches all apps for an intent filter that matches the intent. When a match is found,[3]the system starts the matching activity (Activity B) by invoking its onCreate()method and passing it theIntent
  • 96. Intents Intent Filter Intent filter - an expression in an app's manifest file that specifies the type of intents that the component would like to receive. For instance, by declaring an intent filter for an activity, you make it possible for other apps to directly start your activity with a certain kind of intent. Likewise, if you do not declare any intent filters for an activity, then it can be started only with an explicit intent.
  • 97. Intents Intent Filter The system may send a given Intent to an activity if that activity has an intent filter fulfills the following criteria of the Intent object: Action - A string naming the action to perform. Data - A description of the data associated with the intent. Category - an additional way to characterize the activity handling the intent, usually related to the user gesture or location from which it's started.
  • 98. Intents Intent Filter For example, here's an activity with an intent filter that handles the ACTION_SENDintent when the data type is either text or an image:
  • 99. Intents Intent Filter
  • 100. Working with Services
  • 101. Android Services Is a component which runs in the background without direct interaction with the user Used for repetitive and long running operations, e.g., downloads, polling for data Is not on a separate process (otherwise explicitly defined), but is in the same process as the application Is not a thread, but rather it works as a decoupled component that can execute code independent of other components lifecycles Forms of Services Started Explicitly started by another component Bound Bound to another component Other types of Services IntentService AIDL
  • 102. Android Services
  • 103. started Services Creating a started service Extend the Service-class Override onCreate if one time initializations are needed Override onStartCommand, where the actual work is done Be reminded to call stopService from a component or stopSelf if from within Service Restart Options (returned in onStartCommand) Service.START_STICKY Will restart automatically and call onStartCommand, however, previous intent data will not be present Service.START_NOT_STICKY Does not automatically restart service Service.START_REDELIVER_INTENT
  • 104. bound Services Creating a bound service Extend the Service-class Override onCreate if one time initializations are needed Override onBind and return a valid IBinder-implementor Create an instance of ServiceConnection bound services Create a common Service Restart Options (returned in onStartCommand) Service.START_STICKY Will restart automatically and call onStartCommand, however, previous intent data will not be present Service.START_NOT_STICKY Does not automatically restart service Service.START_REDELIVER_INVERSE
  • 105. IntentService A straightforward structure for running an operation on a single background thread Service requests sequentially processed Has its own worker thread Must only override onHandleIntent rather than startCommand Auto start and stop when task are finished More ideal for doing simple fire and forget calls like sending emails or posting a request
  • 106. BroadcastReceiver
  • 107. BroadcastReceiver is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens. applications can register for a particular event. Once the event occurs, the system will notify all the registered applications. jobistopass a notification to the user, in case a specific event occurs.
  • 108. BroadcastReceiver Two type of registration can be registered via the AndroidManifest.xml file.
  • 109. BroadcastReceiver Two type of registration dynamic, which is done using Context.registerReceiver() method. Dynamically registered broadcast receivers can be unregistered using Context.unregisterReceiver() method. intentFilter = new IntentFilter(); intentFilter.addAction("SMS_RECEIVED_ACTION"); registerReceiver(intentReceiver, intentFilter);
  • 110. BroadcastReceiver Creation Extend BroadcastReceiver abstract class. Implement onReceive() Register to AndroidManifest.xml or in an Activity. You may provide a Notification for the received result. For some events we may require permissions. For example to use We need to add:
  • 111. SQLite and ContentProvider
  • 112. What is SQLite? Open-source (Yeah!) A full-featured relational database (transactional etc.) Supports standards SQL Very lightweight (only ~250KB) Fully embeddable (self-contained) Dynamically Typed No need to setup, just create a database (CREATE- statements) and Android will manage the rest (serverless) Does I/O in filesystem, so it should be run asynchronously Default location is at /data/data//dabases/
  • 113. What is SQLite? Storage Classes NULL INTEGER REAL TEXT BLOB Booleans are either 0 or 1 INTEGERs Dates/times are TEXT, INTEGER, or REAL
  • 114. SQLiteDatabase Exposes methods to manage a SQLite database Has methods to create, delete, execute SQL commands, and perform other common database management tasks Database names must be unique only within the app, not across all applications Key Methods beginTransaction/endTransaction query/rawQuery execSQL update delete insert
  • 115. Cursor and ContentValues Cursors Provides an interface to random read-write access to the result set returned by a database query Similar to your ResultSet in Java (JDBC) Common Types MergeCursor Designed to concatenate two data sets "vertically", adding more rows (like UNION) CursorJoiner Designed to concatenate two data sets "horizontally", adding more columns (like a SQL JOIN) MatrixCursor Allows you to build something that implements the Cursor interface out of pure data AbstractCursor Allows you to wrap your own custom data set in a Cursor interface, overriding the methods that are necessary ContentValues A key-value pair data structure for use in SQLiteDatabase transactions in Android
  • 116. SQLiteOpenHelper A helper class to manage database creation and version management Takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary Transactions are used to make sure the database is always in a sensible state Key Methods to Override onCreate(sqliteDatabase) Called upon first access to the database onUpgrade(sqliteDatabase, oldVersion, newVersion) Called when current database version differs from a new one onOpen(sqliteDatabase) Called upon opening a SQLiteDatabase
  • 117. ContentProvider Manages access to a central repository of data Primarily intended to be used by other applications, which access the provider using a provider client object Applications access a ContentProvider data through a ContentResolver object from a Context Data can be accessed or modified via a Content URI (Ex. content://com.safeway.client/savings/weeklyads)
  • 118. ContentProvider Manages access to a central repository of data Primarily intended to be used by other applications, which access the provider using a provider client object Applications access a ContentProvider data through a ContentResolver object from a Context Data can be accessed or modified via a Content URI (Ex. content://com.safeway.client/savings/weeklyads)
  • 119. Conventions
  • 120. SharedPreferences
  • 121. SharedPreferences The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. data will persist across user sessions (even if your application is killed). Are only for reading & writing key-value pairs and you should not confuse them with the Preference APIs, which help you build a user interface for your app settings (although they use SharedPreferences as their implementation to save the app settings).
  • 122. SharedPreferences Two methods to use: getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter. Context context = getActivity(); SharedPreferences sharedPref = context.getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE); * opens it using the private mode so the file is accessible by only your app. *When naming your shared preference files, you should use a name that's uniquely identifiable to your app, such as "com.example.myapp.PREFERENCE_FILE_KEY"
  • 123. SharedPreferences Two methods to use: getPreferences() Use this from an Activity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name. SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
  • 124. SharedPreferences Writing a SharedPreference: create a SharedPreferences.Editor by calling edit() on your SharedPreferences. Pass the keys and values you want to write with methods such as putInt() and putString(). Then call commit() to save the changes. SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.saved_high_score), newHighScore); editor.commit();
  • 125. SharedPreferences Read a SharedPreference: call methods such as getInt() and getString(), providing the key for the value you want, and optionally a default value to return if the key isn't present SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); int defaultValue = getResources().getInteger(R.string.saved_high_score_default); long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
  • 126. Connecting to the Internet Day II
  • 127. Connecting to the Internet java.net.* android.net.*
  • 128. Connecting to the Internet Choose an HTTP Client HttpURLConnection ApacheHttpClient *Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling. *Recommend usingHttpURLConnectionfor applications targeted at Gingerbread and higher.
  • 129. Connecting to the Internet Perform Network Operations on a Separate Thread The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. new LoginTask().execute(params);
  • 130. Connecting to the Internet The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread. enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.
  • 131. Connecting to the Internet AsyncTask's generic types: Params, the type of the parameters sent to the task upon execution. Progress, the type of the progress units published during the background computation. Result, the type of the result of the background computation. Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void: private class MyTask extends AsyncTask { ... }
  • 132. Connecting to the Internet AsyncTask's Process:
  • 133. Connecting to the Internet 4 Steps onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  • 134. Connecting to the Internet 4 Steps doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  • 135. Connecting to the Internet 4 Steps onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  • 136. Connecting to the Internet 4 Steps onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
  • 137. Connecting to the Internet Threading rules There are a few threading rules that must be followed for this class to work properly: The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN. The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)
  • 138. Connecting to the Internet Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
  • 139. Connecting to the Internet There are two main uses for a Handler: to schedule messages and runnables to be executed at some point in the future; and to enqueue an action to be performed on a different thread than your own.
  • 140. The Android Manifest
  • 141. The Android Manifest Defines components and settings Provides additional meta-data for the application Ex. icons, app name, or the app version Provides certain qualifiers and/or configuration for the PackageManager/Google Play Ex. Minimum Android version the app requires or the devices that can download and install the app It is where you define what permissions, features, or libraries the application needs and requests Ex. Declarion of the app on what 3rd party system library it uses or what permission it requires, e.g. INTERNET
  • 142. AndroidManifest.xml Key Elements
  • 143. The root element of the AndroidManifest.xml file It must contain an element and specify xmlns:android and package attributes Key Attributes xmlns:android Always set to http://schemas.android.com/apk/res/android Package A full Java-language-style package name for the application The name should be unique, as this identifies your application android:versionCode Internal version number; Rule of thumb would be to follow the revision no. of the code android:versionName The version visible to the users android:installLocation Either auto, internalOnly, or preferExternal
  • 144. Allows you to target and specify the applications desired minimum and/or maximum Android version Key Attributes minSdkVersion Defines the minimum Android version the application can work on Used to filter your device out in Google Play If omitted, will assume app will work even on the first version targetSdkVersion Defines the Android version the application was tested on and targets If omitted, will assume version specified in minSdkVersion maxSdkVersion Defines the maximum Android version the application can may work on Not recommended anymore as it will be deprecated soon
  • 145. API Level/Version An integer value that uniquely identifies the framework API revision offered by a version of the Android platform
  • 146. Requests a permission that the application must be granted in order for it to operate correctly Permission are granted upon installation Key Attributes android:name The name of the permission Ex. android.permission.INTERNET or android.permission.CAMERA android:maxSdkVersion The max version the application will request for a specific permission Ex. android.permission.WRITE_EXTERNAL_STORAGE will not be granted beginning KitKat as it is being deprecated
  • 147. The declaration of the application Where all components must be declared in Key Attributes android:icon The applications icon android:label The application name android:name A reference to the apps Application-class android:theme A reference to a style that the whole application will use
  • 148. Specifies the types of intents that an activity, service, or broadcast receiver can respond to Declares what the component can handle Key Elements Required
  • 149. Declares an action that a component can handle Can be declared multiple times, but recommended is to decouple and create separate For an intent to pass, must match one of the actions declared Key Attributes android:name The defined action that the intent can/may handle Recommended is to use a package prefixed action Ex. com.safeway.client.android.ACTION_MYLIST
  • 150. Declares a action that a component can handle Can be declared multiple times, but recommended is to decouple and create separate For an intent to pass, all categories declared must be included in the intent Key Attributes android:name The defined category that the intent can/may handle Recommended is to use a package prefixed category Ex. com.safeway.client.android.CATEGORY_EDIT
  • 151. Declares a data or URI or MIME-type the component can/may handle Attributes are optional, but are mutually dependent ://:/[]|(other path-attributes) Key Attributes android:scheme Examples are http or tel android:host Examples are com.safeway.client or a telephone number android:port Examples are 8080 or 5555 android:path Examples are /helloworld or /someSubPath
  • 152. Declares an activity that implements part of the application's visual user interface Every activity must be declared to shown Key Attributes android:configChanges Lists configuration changes that the activity will handle itself Ex. orientation or locale android:icon Activitys unique icon android:label Activitys visible name when in foreground android:name A reference to the Activitys implementing class android:screenOrientation The orientation of the activity's display on the device
  • 153. Key Attributes (continued) android:launchMode standard (creation) Default. The system always creates a new instance of the activity in the target task and routes the intent to it. singleTop (creation) If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity. singleTask (task) The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one. singleInstance (task) Same as "singleTask", except that the system doesn't launch any other activities into the task holding the instance. The activity is always the single and only member of its task.
  • 154. Declares a service (a Service subclass) as one of the application's components Key Attributes android:icon Services unique icon android:label Services visible name when in foreground android:name A reference to the Services implementing class android:process The name of the process where the service is to run If starting with :, will create (if necessary) a private process for the application Else, it will create a global process that can be shared (resource sharing)
  • 155. Declares a broadcast receiver (a BroadcastReceiver subclass) as one of the application's components Key Attributes android:icon BroadcastReceivers unique icon android:label BroadcastReceivers visible name when in foreground android:name A reference to the BroadcastReceivers implementing class android:enabled If enabled, receiver will be able to listen to intents it can handle Default value is true android:process
  • 156. Declares a content provider (a ContentProvider subclass) as one of the application's components Key Attributes android:authorities Used to identify what URIs the content provider offers Must declare at least one authority android:name A reference to the ContentProviders implementing class android:exported Defines if the content provider is accessible by other applications Default value is true if on API 16 and below, else default is false android:enabled android:process
  • 157. Contacts and Resources SDG Mobile Computing Android Team Michael Angelo M. Rivera [email protected] Deuphil B. Kaufmann [email protected] Official Android Developer site http://developer.android.com Safeway Mobile Development Center http://collab.safeway.com/it/SDLC/mobile/Lists/androi