Android is a stack of operating system, middle ware and applications developed by Google that is dedicated to mobile devices. Android relies on Linux kernel 2.6 for core services. The Android platform provides API and Tools to develop applications using Java Platform. It features Dalvik Virtual Machine, SQLite, an integrated browser, application framework, as well as various media and hardware support.
- A software stack for mobile devices
- Linux Kernel
- Standard services
- Android specific
- Libraries
- System C library - Bionic libc
- Surface manager - Display management
- Media framework - Audio/Video
- Webkit - Browser engine
- OpenGL - Graphics engine
- Webkit - Relational database engine
- Android Runtime
- Core Java libraries
- Basic java classes - java.*, javax.*
- Application lifecycle - android.*
- Internet/Web services - org.*
- Unit testing - junit.*
- Dalvik virtual machine
- where applications are excuted
- Designed for resource-constrained environments
- where applications are excuted
- limited battery life, less RAM, and slower CPU
- Application Framework
- Package Manager - keeps track of application packages on device
- Windows Manager - manages the windows comprising and application
- View System - provides common user interface elements
- Resource Manager - manages non-compiled resources
- Activity Manager - manages application lifecycle and navigation stack
- Content Provider - inter-application data sharing
- Location Manager - provides location & movement information
- Notification Manager - place notification icons in the status bar when important events occur
Android Fundamental
- Activity
- Primary class for user interaction
- Usually implements a single, focused task that the user can do
-
Activity is the presenter of a single screen in the application. It has certain abilities, like displaying views, menus, alerts and notifications. It can also call another Activity, which means opening a new screen.
Activity is a class that derives from an android.app.Activity.
An application needs to have at least one Activity.
All Activities must be declared in the manifest file.
- Service
-
A Service is an application that has the ability to run in the background without displaying any user interface.
A Service is a class that derives from android.app.Service.
All Services must be declared in the manifest file.
- Run in the background
- To perform long-running operations
- To support interaction with remote processes
- BroadcastReceiver
- Component that listens for and responds to events
- The subscriber in publish/subscribe pattern
- Events represented by the Intent class and the broadcast
- BroadcastReceiver receives and responds to broadcast event
- Content Providers
- Store & share data across applications
- Uses database-style interface
- Handles interprocess communication
- MapLocation
- User enters an address
- Application displays a map of area around the address
Creating an Application
- Define Resources
- Resources are non-source code entities
- User Interface Layout
- UI layout specified in xml files
- XML files typically stored in res/layout/*.xml
- Accessed in Java as: R.layout.layout_name
- Can specify different layout files based on your device’s orientation, screen size, etc.
- Access in java, you refer to them as R.layout. layout_name
- Strings
- Access in java, you refer to them as R.string.string_name
- Images
- Menus
- Animations
- Allows to be customized for different devices and users
- Java code uses the R class to access resources
- At compilation time, resources are used to generate the R.java class
- Implement Application Classes
- Usually involves at least one Activity
- Activity initialization code usually in onCreate()
- Restore saved state
- Set content view
- Initialize UI elements
- Link UI elements to code Actions
- Package Application
- System packages application components & resources into a .apk file
- Developers specify required application information in a file called AndroidManifest.xml
- Application Name Á Components
- Required permissions, Application features, Minimum API level
- Install & Run Application
- Run in the emulator
- Enable USB Debugging on the device
Activity
Provides a visual interface for user interaction and each activity typically supports one focused thing a user can do. Applications often comprise several activities.
Activity is the presenter of a single screen in the application. It has certain abilities, like displaying views, menus, alerts and notifications. It can also call another Activity, which means opening a new screen.
Activity is a class that derives from an android.app.Activity.
An application needs to have at least one Activity.
All Activities must be declared in the manifest file.
- Navigation through Activities
- Android supports navigation in several ways:
- Tasks
- A task is a set of related activities
- These related activities don’t have to be part of the same application/li>
- Most tasks start at the home screen
- The Task Backstack
- when an activity is launched, it goes on top of the backstack
- when the activity is destroyed, it is popped off the backstack/li>
- Suspending & Resuming Activities
- The Activity Lifecycle
- Activities are created, suspended, resumed & destroyed as necessary when an application executes.
- onCreate()
- Called when activity is created
- Sets up initial state
- Call super.onCreate()
- Set the activity’s content view
- Retain references to UI views as necessary
- Configure views as necessary
- onRestart()
- Called if the Activity has been stopped and is about to be started again.
- Typical actions
- Special processing needed only after having been stopped.
- onStart()
- Activity is about to become visible.
- Typical actions
- Start when visible-only behaviors.
- Loading persistent application state.
- onResume()
- Activity is visible and about to start interacting with user.
- Typical actions
- Start foreground-only behaviors.
- onPause()
- Focus about to switch to another activity.
- Typical actions
- Shutdown foreground-only behaviors.
- Save persistent application state.
- onStop()
- Activity is no longer visible to user. May be restarted later.
- Typical actions
- onDestroy()
- Activity is about to be destroyed.
- Typical actions
- Release Activity resources.
- Starting Activities
- Create an Intent object specifying the Activity to start.
- Pass newly created intent to methods, such as:
- startActivity(Intent, ...)
- startActivityForResult(Intent, ...)
- Invokes a callback method when the called activity finishes to return a result
- setResult(int resultCode, Intent)
- Started Activity can set its result by calling setResult().
- RESULT_CANCELED
- RESULT_OK
- RESULT_FIRST_USE
- Custom resultCodes can be added.
- Configuration Changes
- Keyboard, orientation, locale, etc.
- Device configuration can change at runtime.
- On configuration changes, Android usually kills the current Activity & then restarts it.
- Activity restarting should be fast.
- If necessary you can:
- Retain an Object containing important state information during a configuration change
- Hard to recompute data can be cached to speed up handling of configuration changes.
- Override onRetainNonConfigurationInstance() to build & return configuration Object Will be called between onStop() and onDestroy()
- Call getLastNonConfigurationInstance() during onCreate() to recover retained Object
- Manually handle the configuration change
- Can prevent system from restarting Activity.
- Declare the configuration changes your Activity handles in AndroidManifest.xml file.
- <activity android:name=".MyActivity" android:configChanges="orientation|screensize|keyboardHidden"…>
- When configuration changes
- Activity’ s onConfigurationChanged() method is called
- Passed a Configuration object specifying the new device configuration
Intent
-
Intent is the negotiator between two activities or between two applications. It gives the ability to pass messages and data between the two entities.
When writing applications for mobile, Intent gives access to OS services like opening the camera, a browser, displaying notifications and so on.
- A data structure that represents
- An operation to be performed
- An event that has occurred
- Intent as desired operations
- Intents provide a flexible language for specifying operations to be performed.
- Intent is constructed by one component that wants some work done
- Received by one activity that can perform that works
- Intent Fields
- Action - String representing desired operation
- ACTION_DIAL – dial a number
- ACTION_EDIT – display data to edit
- ACTION_SYNC – synchronize device data with server
- ACTION_MAIN – start as initial activity of app
- Data - Data associated with the intent
- Formatted as a URI (uniform resource identifier)
- Category
- Additional information about the components that can handle the intent
- Type
- Specifies the MIME type of the intent data
- Component
- The component that should receive this intent
- Use this when there’s exactly one component that should receive the intent
- Extras
- Add’l information associated with intent
- treated as a map
- Flags
- Specify how intent should be handled
- The target activity
- Can be named explicitly by setting the intent’s component
- Can be determined implicitly
- Implicit activation
- When the activity to be activated is not explicitly named, Android tries to find activities that match the intent
- This process is called intent resolution process
- An intent describing a desired operation
- IntentFilters which describe which operations an activity can handle
- Specified either in AndroidManifest.xml or programmatically
- Intent Resolution Data
- Action
- Data (Both URI & TYPE)
- Category
Permissions
- Android protects resources & data with permissions
- Used to limit access to:
- User information
- cost-sensitive API’s
- System resources
- Permissions are represented as strings
- In AndroidManifest.xml, apps declare permissions
- They require of other components
- Using Permissions
- Apps specify permissions they use through a <uses-permission> tag
- Users must accept these permissions before an application can be installed
- Defining Permissions
- Suppose your application performs a privileged/dangerous operation
- Youu might not want to allow just any application to invoke yours
- So you can define & enforce your own permission
- Component Permissions
- Individual components can set their own permissions, restricting which other components can access them
- Component permissions take precedence over application-level permissions
- Activity permissions
- restricts which components can start the associated
- Checked within execution of
- startActivity()
- startActivityForResult()
- Throws SecutityException on permissions failure
- onCreateView() must return the View at the root of the Fragments’s layout
- This view is added to the containing activity
Fragment
- Represents a behavior / portion of UI within an activity
- Multiple fragments can be embedded in an activity to create a Multi-pane UI
- A single fragment can be reused across multiple activities
- Fragment Lifecycle
- Fragment lifecycle is coordinated with the lifecycle of its containing activity
- Fragments have their own lifecycles and receive their own callbaks
- Fragment State
- RESUMED - Fragment is visible in the running activity
- PAUSED - Another activity is in the foreground and has focus, containing activity is visible
- STOPPED - The fragment is not visible
- Adding Fragments to an Activity’s Layout
- Declare it statically in the Activity’s layout file
- Add it programmatically using the Fragment Manager
- Fragment Layout
- Layout can be inflated/ implemented in onCreateView()
- onCreateView() must return the View at the root of the Fragment’s layout/li>
- This View is added to the containing Activit
- Adding Fragments Dynamically
- While an Activity’s running you can add a Fragment to it’s layout
- Get reference to the FragmentManager/li>
- Begin a FragmentTransaction
- Add the Fragment
- Commit the FragmentTransaction
- Dynamic Layout
- Fragment transactions allow you to dynamically change your app’s user interface
- Can make the interface more fluid & take better advantage of available screen space
- Configuration Changes
- If you call setRetainInstance(true), Android won’t destroy the Fragment on configuration changes
- Results in some changes to lifecycle callback sequence
- onDestroy() will not be called
- onCreate() will not be called
- Tips
- what are the purposes of using a fragment & what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?
- Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;
- The ActionBar. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener interface gives you a FragmentTransaction as an input argument to the onTabSelected method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.
- The FragmentManager handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.
- You can use the cool ViewPager with a FragmentPagerAdapter to create swipe interfaces. The FragmentPagerAdapter code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.
- Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
- You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar, with tabs, overflow, split action bar, viewpager etc.
- The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity() with data on it. The intent is passed on to all fragments of the activity you launch.
User Interface
Activities usually display a user interface and Android provides many classes for constructing user interfaces.
- View
-
A view is a single user interface element. It handles user events and draws the component on the screen.
Views can contain other Views, these are called view groups.
A View is a class that derives from android.view.View.
There are already many existing views. The developer can use them or create his own customized view by extending any of them.
- Key building block for UI components
- Occupy a rectangular space on screen
- Responsible for drawing themselves and for handling events
- Common View Operations
- Set visibility: show or hide view
- Set Checked state
- Set Listeners: Code that should be executed when specific events occur
- Set properties: opacity, background, rotation
- Manage input focus: allow view to take focus, request focus
- View Event Sources
- User interaction
- Touch
- Keyboard/trackball/D-pad
- System control
- Displaying Views
- Views are organized in a Tree
- Displaying has multiple steps
- Measure – get dimensions of each View
- Layout – Position each View
- Draw – Draw each view
- Handling View Events
- Custom View subclasses can override various View methods
- ViewGroup
- An invisible View that contains other views
- Used for grouping & organizing a set of views
- Base class for view containers & layouts
- Adapters & AdapterViews
- AdapterViews are views whose children and data are managed by an Adapter
- Adapter manages the data and provides data views to AdapterView
- AdapterView displays the data Views
- Layout
- Reference: Layout - Structure
- A generic ViewGroup that defines a structure for the Views it contains
- LinearLayout
- Child views arranged in a single horizontal or vertical row
- Respects child's margins, gravity, weight
- RelativeLayout
- Child views are positioned relative to each other and to parent view
- TableLayout
- Child views arranged into rows & columns
- GridView
- Child views arranged in a two-dimensional, scrollable grid
- AbsoluteLayout
- Each child is given absolute x, y location
- Menus and ActionBar
- Activities support menus
- Activities can
- Add items to a menu
- handle clicks on the menu items
- Menu Types
- Options
- menu shown when user presses the menu button
- Context
- View-specific menu shown when user touches and holds the view
- Submenu
- A menu activated when user touches a visible menu item
- Creating Menus
- Define menu resource in XML file
- Store in res/menu/filename.xml
- Inflate menu resource using Menu
- Inflater in onCreate…Menu() methods
- Handling item selection in appropriate on…ItemsSelected() methods
- Menus
- Many other features supported
- Grouping menu items
- Binding shortcut keys to menu items
- Binding Intents to menu items
- ActionBar
- Similar to Application Bar in many desktop applications
- Enables quick Access to common operations
- FragmentDynamicLayout with ActionBar
- Shows play titles and one quote from the selected play
- Provides actions for the ActionBar
- Three main objects
- QuoteViewerActivity
- TitleFragment
- QuoteFragment
- ActionBar.Tab
- Screen is divided into tab & content areas
- Allows multiple Fragments to share single content area
- Each tab is associated with one Fragment
- Exactly one tab is selected at any given time
- Fragment corresponding to the selected tab is visible in the content area
- Dialogs
- Independent subwindows used by Activities to communicate with user
- Dialog Subclasses
- AlertDialog
- ProgressDialog
- DatePickerDialog
- TimePickerDialog
User Notification
BroadcastReceiver
- Base class for components that receive and react to events
- BroadcastReceivers register to receive events in which they are interested
- When Events occur they are represented as Intents
- Those Intents are then broadcast to the system
- Android routes the Intents to BroadcastReceivers that have registered to receive them
- BroadcastReceivers receive the Intent via a call to onReceive()
- Typical Usecase
- Register BroadcastReceivers
- Broadcast an Intent
- Normal vs. Ordered
- Normal: processing order undefined
- Ordered: sequential processing in priority order
- Sticky vs. Non-Sticky
- Sticky:Store Intent after initial broadcast
- Non-Sticky: Discard Intent after initial broadcast
- With or without receiver permissions
- Android delivers Intent to registered recipients by calling their onReceive() method
- Intents delivered by calling onReceive(), passing in:
- the Context in which the receiver is running
- the Intent that was broadcast
- Event handled in onReceive()
- Hosting process has high priority while onReceive() is executing
- onReceive() runs on the main Thread, so it should be short-lived
- If event handling is lengthy, consider starting a Service, rather than performing complete operation in onReceive()
- Receiver is not considered valid once onReceive() returns
- Normally BroadcastReceivers can’t start asynchronous operations
Threads, AyncTasks & Handlers
- UI Thread
- Applications have a main thread (the UI thread)
- Application components in the same process use the same UI thread
- User interaction, system callbacks & lifecycle methods handled in the UI thread
- In addition, UI toolkit is not thread-safe
- Need to do work in a background thread, but update the UI in the UI Thread
-
Android provides several methods that are guaranteed to run in the UI Thread: boolean View.post (Runnable action) Á void Activity."
runOnUiThread (Runnable action)
- AyncTasks
- Provides a structured way to manage work involving background & UI threads
- Background thread performs work and Indicates progress
- UI Thread does setup Publishes intermediate progress and Uses results
- Handler
- A background thread that provides you to communicate with the UI. Updating a progressbar for instance should be done via Handler. Using Handlers you have the advantage of MessagingQueues, so if you want to schedule messages or update multiple UI elements or have repeating tasks.
- Each Handler is associated with a Thread
- One Thread can hand off work to another Thread by sending Messages & posting Runnables to a Handler associated with the other Thread
- Runnable: Contains an instance of the Runnable interface and Sender implements response
- Message: Can contain a message code, an object and integer arguments Handler implements response
- Each Android Thread is associated with a messageQueue & a Looper
- A MessageQueue holds Messages and Runnables to be dispatched by the Looper
- Add Runnables to MessageQueue by calling Handler’s post() method
- Add Messages to MessageQueue by calling Handler’s sendMessage() method
- Looper dispatches Messages by calling the handler’s handleMessage() method in the MessageQueue’s Thread
- Looper dispatches Runnables by calling their run() method in the MessageQueue’s Thread
Alarms
Networking
- Early handheld devices gave us mobility But with limited connectivity
- Today’s devices have greater mobility and connectivity
- Many applications use data and services via the Internet
- Android includes multiple networking support classes,
- java.net – (Socket, URL)
- org.apache - (HttpRequest, HttpResponse)
- android.net – (URI, AndroidHttpClient, AudioStream)
- Networking Permissions
Graphics & Animation
MultiTouch & Gestures
Sensors
Maps & Location
Data Management
- SharedPreferences
- Small amounts of primitive data
- Internal Storage
- Small to medium amounts of private data
- External Storage
- Larger amounts of non-private data
- SQLite databases
- Store small to large amounts of private, structured data
Testing
First write the tests, Then write the code to be tested...
Only way to share data across applications. Typically content provider is used in one of two scenarios; access an exiting content provider in another application, or create a new content provider in your application to share data with other applications.