You are on page 1of 50

Architecting Android Apps

Architecting Android Apps Overview

Marko Gargenta @Marakana

About Marko Gargenta

Marko Gargenta

Entrepreneur, Author, Speaker


Developer of Android Bootcamp for Marakana.
Instructor for 1,000s of developers on Android at Qualcomm, Cisco, Motorola, Intel, DoD and
other great orgs.
Author of Learning Android published by OReilly.
Speaker at OSCON (4x), ACM, IEEE(2x), SDC(2x), AnDevCon(2x), DroidCon.
Co-Founder of SFAndroid.org
Co-Chair of Android Open conference: Android Open

Architecting Android Apps Overview

Architecting Android Apps Overview


The goal of this module is to introduce you to main components used to create
Android apps. By the end of this module, you should have a good idea what
Android app building blocks are, and their key properties.
Seven iterations of an app:
Part 1 - Activities and Android UI
Part 2 - Intents, Action Bar, and More
Part 3 - Services
Part 4 - Content Providers
Part 5 - Lists and Adapters
Part 6 - Broadcast Receivers
Part 7 - App Widgets

Yamba

Yamba

Objectives of Yamba
The objective of this module is to explain how to go about designing a typical
Android app. You will have a chance to see an example app, Yamba, using most of
the standard Android building blocks. By the end of this talk, you should have
high-level understanding about designing an Android app.

Yamba Approach
Yamba Overview
Yamba: Yet Another Micro-Blogging App
Comprehensive Android example application.
Works with services that support Twitter API.

Project Philosophy
Small increments - build it organically
App must always run - whole and complete
Refactor when needed - do simplest thing first

Part 1 - Activities and Android UI

Yamba Part 1

Activity Overview

Example of Activities

An activity is roughly a screen.


A typical application may have many activities.
Activities are typically expensive and so are managed by the system.

Activity Lifecycle

Activity Lifecycle

Activities are highly managed by the systems ActivityManager.


ActivityManager drives the activity through its states.
You as an app developer get to say what happens on transitions.

Activity Callbacks
Lifecycle

onCreate()
Used to setup your activity. You will almost always have to have it. Good place to
inflate the UI and setup listeners.

onResume()and onPause()
Use them to turn on and off things that youd like to have running only while the
activity is visible. This is important for things that consume a lot of battery, such
as GPS and sensors.

onStart()and onStop()
Use to setup code that starts/stops the activity. Unlike onResume()and
onPause(), it includes Paused state as well.

onRestart()
Called when the activity is restarted. It is followed by onStart()and
onResume().

onDestroy()
A good place to do any cleanup before the activity is cleaned up from memory.
This is the counter-part to onCreate().

Other

onCreateOptionsMenu()and
onOptionsItemSelected()
Use them to setup your menu. onOptionsItemSelected()loads the menu,
typically from an XML resource. onOptionsItemSelected()is called whenever
an option menu item is clicked on.

Various listeners and event handlers, such as onClick()


Used to handle the UI events.

Registering Activity
Main Activity
Register the activity in the Android Manifest file:
Android Manifest file
...
<activity
android:name=".ActivityDemo"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
...

The intent filter specifies that this activity is to be the main entry point into the
application as well as that it should be shown in the app launcher on home screen.

Any other activity


Android Manifest file
...
<activity android:name=".AnotherActivity"></activity>
...

Building Android UI
There are two approaches to building Android UI:

Declaratively
Declare UI in XML
Eclipse provides nice drag-n-drop tools
Inflate the XML views in Java

Programmatically
Instantiate all widgets programmatically
Set properties for each

The best is to use both:


1.

Star with declaring the look and feel using XML

2.

Inflate XML into Java

3.

Finish by programming the actions using Java

Layouts and Views

Layouts and Views

Part 2 - Intents, Action Bar, and More

Yamba Part 2

Intent Overview

Example of Intents

Intents are like events or messages.


You can use them so start activities, start/stop services, or send broadcasts.
Intents can be implicit or explicit.

Using Intents
startActivity()
Starts an activity specified by the intent. If activity does not exist already, it calls
onCreate()to create it. Otherwise, it calls onStart()and onResum().

startService()
Starts a service. Even if the service is not created yet, it called onCreate()on
the service first.

stopService()
Stops a service that is already running. If service is not running, it does nothing.

bindService()
Binds to a service. Requires that the service returns a binder via onBind()
method.

sendBroadcast()
Sends a broadcast. If theres a broadcast receiver registered to filter for the same
action as this intent is specifying, that receivers onReceive()method will be
called.

Explicit and Implicit Intents


Explicit Intent
ActivityDemo.java
...
startActivity(new Intent(this, AnotherActivity.class));
...
startService(new Intent(this, ServiceDemo.class));
...

thisis the context from which this intent is being sent, in our case an Activity.

Implicit Intent
ActivityDemo.java
...
startService(new Intent("marakana.intent.action.IntentServiceDemo"));
...
sendBroadcast(new Intent("marakana.intent.action.ReceiverDemo"));
...

Requires that theres an intent filter filtering for this particular intent, for example:
AndroidManifest.xml
...
<service android:name=".IntentServiceDemo">
<intent-filter>
<action android:name="marakana.intent.action.IntentServiceDemo" />
</intent-filter>
</service>
...
<receiver android:name=".ReceiverDemo">
<intent-filter>
<action android:name="marakana.intent.action.ReceiverDemo" />
</intent-filter>
</receiver>
...

Intent Filter
Intent filter is a way for us to assign certain action to an activity, service, receiver
or similar.
Action is one of system defined actions, or something you come up with.
Intent filter typically goes into Android Manifest file, within <activity>,
<service>, or <receiver>elements.
Android Manifest file
...
<intent-filter>
<action android:name="some.action.goes.here" />
</intent-filter>
...

Action Bar
The action bar, introduced in Honeycomb (API 11) is a title bar that includes:
The application icon
The activity title
A set of user-selectable actions (optional)
A set of user-selectable navigation modes (optional)

Enabling the Action Bar


Android automatically displays an action bar on an API 11+ system if the <usessdk>element of your applications manifest:
Sets minSdkVersionto 11 or later, or
Sets targetSdkVersionto 11 or later

Either or these settings enable the "holographic look and feel" introduced in
Honeycomb, which includes action bar support.
If neither minSdkVersionnor targetSdkVersionare set to 11+, then an API 11+ system
renders the app in a legacy theme, without action bar support.

With the action bar enabled, legacy option menu items appear automatically in
the action bars overflow menu. You reveal the overflow menu with:
The hardware Menu button (if present), or
An additional button in the action bar (for devices without a hardware Menu button)

Adding Action Items


<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_save"
android:icon="@drawable/ic_menu_save"
android:title="@string/menu_save"
android:showAsAction="ifRoom|withText" />
</menu>

To display an option menu item as an action item, in the menu resource file add
android:showAsAction="ifRoom"to the <item>element.
The device will display the item if there is room available in the action bar, otherwise the item
appears in the overflow menu.
Devices running API 10 or earlier ignore the showAsActionattribute.

If your menu item supplies both a title and an icon, the action item shows only the
icon by default.
To display the text title, add withTextto the android:showAsActionattribute. For
example:
The withTextvalue is a hint to the action bar. The action bar will show the title if possible, but
might not if an icon is available and the action bar is constrained for space.

Part 3 - Services

Yamba Part 3

Service Overview

Example of a Service

Services are code that runs in the background.


They can be started and stopped. Services doesnt have UI.
Keep in mind that service runs on the main application thread, the UI thread.

Service Lifecycle

Service Lifecycle

Service starts and "runs" until it gets a request to stop.


Service will run on the main UI thread.
To offload work from main thread, use intent service.
Intent service uses worker thread, stops when done with work.
Services can be bound or unbound.

Service Callbacks
onBind()
Required, but for unbound services, we just return null.

onCreate()
Called when service is first created.

onStartCommand()
Called is called every time service is started.

onDestroy()
Called when service is stopped. It is subsequently destroyed.

IntentService Callbacks
Constructor
It needs to pass the name of this service to its super.

onCreate()
Called when service is first created.

onHandleIntent()
This is where the work of the service runs.

onDestroy()
Called when service is stopped. It is subsequently destroyed.

Registering Service
Registering a service that will be called explicitly by its class name
...
<service android:name=".ServiceDemo"></service>
...

Registering a service that will be called via action


...
<service android:name=".IntentServiceDemo">
<intent-filter>
<action android:name="marakana.intent.action.IntentServiceDemo" />
</intent-filter>
</service>
...

Part 4 - Content Providers

Yamba Part 4

Content Provider Overview

Example of Content Provider

Content Providers share content with applications across application boundaries.


Examples of built-in Content Providers are:
Contacts
MediaStore
Settings and more.

Typical Usage of Content Providers

Typical Usage of Content Providers

Content Provider Lifecycle

Content Provider Lifecycle

Content provider is initiated first time it is used via a call to onCreate().


There is no callback for cleaning up after the provider.
When modifying the data (insert/update/delete), open/close database atomically.
When reading the data, leave database open or else the data will get garbage collected.

Content Provider Callbacks


onCreate()
Used to initialize this content provider. This method runs on UI thread, so should
be quick. Good place to instantiate database helper, if using database.

getType()
Returns the mime time for the given uri. Typically, this MIME type will either be
something like
vnd.android.cursor.item/vnd.marakana.android.lifecycle.status
for a single item or
vnd.android.cursor.dir/vnd.marakana.android.lifecycle.status
for multiple items.

insert()
Inserts the values into the provider returning uri that points to the newly inserted
record.

update()
Updates records(s) specified by either the uri or selection/selectionArgs
combo. Returns number of records affected.

delete()
Deletes records(s) specified by either the uri or selection/selectionArgs
combo. Returns number of records affected.

query()
Queries the provider for the record(s) specified by either uri
or`selection`/selectionArgs/grouping/havingcombo.

Registering Content Provider


Registering in Android Manifest file
...
<provider
android:name=".ProviderDemo"
android:authorities="com.marakana.android.lifecycle.providerdemo" />
...

The authority of this provider must match the uri authority that this provider is
responding to.

Part 5 - Lists and Adapters

Yamba Part 5

Lists and Adapters Overview

Lists and Adapters Overview

Adapters connect potentially large data sets to small views

Fragments

Fragments

So, Whats a Fragment?


A fragment is a class implementing a portion of an activity.
A fragment represents a particular operation or interface running within a larger activity.
Fragments enable more modular activity design, making it easier to adapt an application to
different screen orientations and multiple screen sizes.
Fragments must be embedded in activities; they cannot run independent of activities.
Most fragments define their own layout of views that live within the activitys view hierarchy.
However, a fragment can implement a behavior that has no user interface component.
A fragment has its own lifecycle, closely related to the lifecycle of its host activity.
A fragment can be a static part of an activity, instantiated automatically during the activitys
creation.
Or, you can create, add, and remove fragments dynamically in an activity at run-time.

Loaders
Loaders make it easy to load data asynchronously in an activity or fragment.
Loaders have these characteristics:
They are available to every Activity and Fragment.
They provide asynchronous loading of data.
They monitor the source of their data and deliver new results when the content changes.
They automatically reconnect to the last loaders cursor when being recreated after a
configuration change. Thus, they dont need to re-query their data.

Loaders were introduced in Honeycomb (API 11).


The Android Support Package includes support for loaders. By including the support package in
your application, you can use loaders even if your application for a minSdkVersionof 4 or
later.

Using Loaders in an Application


An application that uses loaders typically includes the following:
An Activityor Fragment.
An instance of the LoaderManager.
A CursorLoaderto load data backed by a ContentProvider. Alternatively, you can
implement your own subclass of Loaderor AsyncTaskLoaderto load data from some other
source.
A data source, such as a ContentProvider, when using a CursorLoader.
An implementation for LoaderManager.LoaderCallbacks. This is where you create new
loader instances and manage your references to existing loaders.
A way of displaying the loaders data, such as a SimpleCursorAdapter.

Availability of Fragments and Loaders


Fragments: Implemented in Honeycomb (3.0) or Later
Fragments were added to the Android API in Honeycomb, API 11.
The primary classes related to fragments are:

android.app.Fragment
The base class for all fragment definitions

android.app.FragmentManager
The class for interacting with fragment objects inside an activity

android.app.FragmentTransaction
The class for performing an atomic set of fragment operations

Fragments: Implemented in Donut (1.6) or Later


Google provides the Compatibility Package, a Java library that you can include in an
application, implementing support for fragments and other Honeycomb features
(loaders).

Part 6 - Broadcast Receivers

Yamba Part 6

Broadcast Receiver Overview

Broadcast Receiver Lifecycle

An Intent-based publish-subscribe mechanism.


Great for listening system events such as SMS messages.

Broadcast Receiver Callbacks


onReceive()
This is the only method you typically care about for a broadcast receiver. It is
called when this receiver is invoked.

Registering Broadcast Receiver


Registering in Android Manifest file
<receiver android:name=".ReceiverDemo">
<intent-filter>
<action android:name="marakana.intent.action.ReceiverDemo" />
</intent-filter>
</receiver>

Registering programmatically
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
// Create the receiver
receiver = new TimelineReceiver();
filter = new IntentFilter( UpdaterService.NEW_STATUS_INTENT );
}
protected void onResume() {
super.onResume();
super.registerReceiver(receiver, filter,
"com.marakana.yamba.SEND_TIMELINE_NOTIFICATIONS", null);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
...

Part 7 - App Widgets

Yamba Part 7

App Widgets Overview


App widgets are miniature views that can live in other apps, such as Home app.
They are a special implementation of Broadcast Receivers.

Declaring an App Widget


Widgets are essentially Broadcast Receivers
Yamba App Widget registration in AndroidManifest.xml
<receiver
android:name=".YambaWidget"
android:label="@string/app_name" >
<intent-filter>
<action android:name="com.marakana.broadcast.NEW_STATUS" />
</intent-filter>
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/widget" />
</receiver>

Specifying Meta Data


Meta data specifies the default size of the widget, plus the update period.
Yamba Widget meta data
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minHeight="72dp"
android:minWidth="294dp"
android:updatePeriodMillis="10000" >
</appwidget-provider>

Yamba App Widget Output

Yamba App Widget Output

Quiz
1.

Name four main Android app building blocks.

2.

What is an activity?

3.

Name major callback methods of an activity.

4.

What is a service?

5.

Name major callback methods of a service.

6.

What is a broadcast receiver?

7.

Name major callback methods of a broadcast receiver.

8.

What is a content provider?

9.

Name major callback methods of a content provider.

10.

What does an Android app consist of?

Architecting Android Apps Summary


This module was an introduction to main components that make up an app. By
now, you should know of activities, services, providers and receivers as well as
intents and other major components of an app.

Architecting Android Apps Summary


Thank you!
Marko Gargenta & Marakana Team
@MarkoGargenta
Special thanks to Ken Jones as well as the rest of Marakana team for research
related to Fragments, Loaders, and many other new features of ICS.
Slides & video of this presentation is available at Marakana.com
Yamba source code is available at https://github.com/marakana/yamba
(c) Marakana.com

You might also like