Android Development

Android Development - 2
Prabhaker Mateti
CEG436: Mobile Computing
Android.os classes, debug refresher
Activities and Tasks
Processes and Threads
Android Location Service
Google Maps External Library
Code Example: SimpleNetworking
Code Example: Android Location Service
CEG436: Mobile Computing (PM)
android.os interfaces
• Provides basic operating system services,
message passing, and inter-process
communication on the device.
• Handler.Callback
• Ibinder interface for a remotable object RPC
• IBinder.DeathRecipient
• Iinterface Base class for Binder interfaces.
• Parcelable cf. serializable, marshalled result
• RecoverySystem.ProgressListener
CEG436: Mobile Computing (PM)
android.os classes
• AsyncTask<Params, Progress, Result> enables proper
use of the UI thread.
• BatteryManager
• Binder remotable object; RPC mechanism defined by
• Bundle A mapping from values to Parcelable types.
• ConditionVariable a locking paradigm.
• Environment
• MemoryFile wrapper for the Linux ashmem
(Anonymous SHared MEMory) driver.
CEG436: Mobile Computing (PM)
android.os classes
• Parcel Container for a message (data and
object references) that can be sent through an
• PatternMatcher A simple pattern matcher;
not full reg-exp, only simple globbing.
• RecoverySystem the separate partition that
can be used to install system updates, wipe
user data, etc.
• StrictMode while developing …
CEG436: Mobile Computing (PM)
• debugging functions for Android applications,
including tracing and allocation counts.
• startMethodTracing(String traceName, int
bufferSize, int flags)
• dumpService (String name, FileDescriptor fd,
String[] args)
• getMemoryInfo (Debug.MemoryInfo
• threadCpuTimeNanos ()
CEG436: Mobile Computing (PM)
• public FileOutputStream (File file, boolean
• public void write (byte[] buffer, int offset, int
• public void close ()
• BufferedOutputStream
CEG436: Mobile Computing (PM)
• FileInputStream(String path) Equivalent to
new FileInputStream(new File(path)).
• public int read (byte[] buffer, int offset, int
• public void close ()
• BufferedInputStream.
CEG436: Mobile Computing (PM)
Application Components
• Activity
– represents a single screen with a user interface.
• Service
– runs in the background; Long-running; for remote processes
– no user interface.
• Content provider
– manages a shared set of application data.
• Broadcast receiver
– responds to broadcast announcements.
• An application can have multiple instances of the above four types.
• Each component is a different point through which the system can
enter an application.
• Every component has a managed lifecycle.
package android.widget
• App Widgets are miniature application views that
can be embedded in other applications (such as
the Home screen) and receive periodic updates.
• App Widgets provide users access to some of
your application features directly from the Home
screen (without the need to launch an activity)
• App Widgets are backed by a special kind of
broadcast receiver that handles the App Widget
CEG436: Mobile Computing (PM)
Live Wallpapers
• similar to a regular Android service.
• consumes CPU time, memory, battery
• onCreateEngine() whose goal is to create a
• source code example: android-sdk-linux_x86/
CEG436: Mobile Computing (PM)
• An Activity is an application component that
provides a UI screen
– e.g., dial the phone, take a photo, send an email,
or view a map.
• Each activity is given a window.
– typically fills the screen, but
– may be smaller than the screen
– float on top of other windows
CEG436: Mobile Computing (PM)
• One activity can start another, including one
defined in a different application.
• Context.startActivity(Intent)
• Activity.startActivityForResult (Intent,
• Asynchronous Message (Intent)
CEG436: Mobile Computing (PM)
public abstract class Context
• extends java.lang.Object
– Interface to global information about an application
– implementation is provided by the Android system.
• Selected methods
File getExternalFilesDir(String type)
FileOutputStream openFileOutput(String name, int mode)
Intent registerReceiver (BroadcastReceiver, IntentFilter, String
broadcastPermission, Handler scheduler)
void sendBroadcast(Intent intent, String receiverPermission)
void startActivities(Intent[] intents)
Object getSystemService(String name)
ComponentName startService(Intent service)
CEG436: Mobile Computing (PM)
Activities vs Tasks (Apps)
• A concrete class in the API
• An encapsulation of a
particular operation
• They run in the process of
the .apk which installed
• Optionally associated
with a window (UI)
• Have an execution
CEG436: Mobile Computing
• More of a notion than a
concrete API entity
• A collection of related
• Capable of spanning
multiple processes
• Associated with their own
UI history stack
• What users on other
platforms know as
public static final int FIRST_APPLICATION_UID
public Process ()
public static final void killProcess (int pid)
public static final void sendSignal (int pid, int
• public static final int getThreadPriority (int tid)
• public static final void setThreadPriority (int
CEG436: Mobile Computing (PM)
• When the first of an application's components
needs to be run, Android starts a Linux
process for it with a single thread of execution
(Main Thread).
• Android may decide to kill a process to reclaim
CEG436: Mobile Computing (PM)
• We can specify a process where an individual
component should run by setting a process name to
“process” attribute of <activity>, <service>, <receiver>,
or <provider>.
– Each component can run in its own process.
– Some components share a process while others do not.
– Components of different applications also can run in the
same process.
• We can set a default value that applies to all
components by setting a default process to “process”
attribute of <application>.
CEG436: Mobile Computing (PM)
Main Thread
• All components are instantiated in the main
thread (aka UI thread) of the specified
• System calls to the components are
dispatched from the main thread.
• Methods that respond to those calls always
run in the main thread of the process.
• Main thread components should not perform
long or blocking operations (e.g., network
downloads, heavy computation loops)
CEG436: Mobile Computing (PM)
Worker Threads
• Anything that may not be completed quickly
should be assigned to a different thread.
• Threads are created in code using standard Java
Thread objects.
• android.os.Looper for running a message loop
within a thread
• android.os.Handler for processing messages
• android.os.HandlerThread for starting a new
thread that has a looper.
CEG436: Mobile Computing (PM)
Thread Issues
• If the UI thread is blocked for more than a few
– "application not responding" (ANR) dialog
• Andoid UI toolkit is not thread-safe.
• Two rules to follow:
– Do not block the UI thread
– Do not access the Android UI toolkit from outside
the UI thread
CEG436: Mobile Computing (PM)
• Perform asynchronous work on user interface.
– Does the blocking operations in a worker thread and then
publishes the results on the UI thread,
– without requiring you to handle threads and/or handlers
• taskA extends AsyncTask
• implement the doInBackground()
– runs in a pool of background threads.
– implement onPostExecute(), which delivers the result from
the above and runs in the UI thread
• run the taskA by calling execute() from the UI thread.
CEG436: Mobile Computing (PM)
Linux v Android Process Basics
• Android process == Linux process
– w/ its own unique UID
• By default, 1 process per .apk
• By default, 1 thread per process
• Most components interleave events into the
main thread
CEG436: Mobile Computing (PM)
Process Lifecycles
• Android tries to maintain a process for as long
as possible, but eventually it may have to
remove some processes when memory runs
• To determine candidates to be killed, Android
places each process into an "importance
hierarchy“ of 5 levels based on the
components running in it and the state of
those components.
CEG436: Mobile Computing (PM)
Foreground process
• A process that is required for what the user is currently doing.
• A process is considered to be in the foreground if it hosts:
an Activity that the user is interacting with
a Service that's bound to the activity that the user is interacting with.
a Service that has called startForeground().
a Service that's executing one of onCreate(), onStart(), or onDestroy().
a BroadcastReceiver that's executing its onReceive() method.
• Generally, only a few foreground processes exist at any given time.
– They are killed only as a last resort—if memory is so low that they
cannot all continue to run.
– Generally, at that point, the device has reached such a state that killing
some foreground processes is required to keep the user interface
CEG436: Mobile Computing (PM)
Visible process
• A process that does not have any foreground
components, but still can affect what the user sees on
• A process is considered visible if it hosts:
– an Activity that is not in the foreground, but is still visible
to the user (its onPause() method has been called).
– a Service that's bound to a visible (or foreground) activity.
• A visible process is considered extremely important
and will not be killed unless doing so is required to
keep all foreground processes running.
CEG436: Mobile Computing (PM)
Service process
• A process that is running a service that has been
started with the startService() method and does
not fall into either of the two higher categories.
• Service processes are not directly tied to anything
the user sees. However, they are generally doing
things that the user cares about (such as playing
music in the background or downloading data on
the network), so the system keeps them running
unless there's not enough memory to retain them
along with all foreground and visible processes.
CEG436: Mobile Computing (PM)
Background process
• A process holding an activity that's not currently visible to the user
(the activity's onStop() method has been called).
• These processes have no direct impact on the user experience, and
the system can kill them at any time to reclaim memory for a
foreground, visible, or service process.
• Usually there are many background processes running, so they are
kept in an LRU (least recently used) list to ensure that the process
with the activity that was most recently seen by the user is the last
to be killed. If an activity implements its lifecycle methods correctly,
and saves its current state, killing its process will not have a visible
effect on the user experience, because when the user navigates
back to the activity, the activity restores all of its visible state.
CEG436: Mobile Computing (PM)
Empty process
• A process that doesn't hold any active
application components.
• The only reason to keep this kind of process
alive is for caching purposes, to improve
startup time the next time a component
needs to run in it. The system often kills these
processes in order to balance overall system
resources between process caches and the
underlying kernel caches.
CEG436: Mobile Computing (PM)
Activities and Tasks
• A task is a collection of related Activities.
• It is capable of spanning multiple processes.
Application1 (.apk)
Application2 (.apk)
Content Provider
CEG436: Mobile Computing (PM)
Content Provider
Activities and Tasks
• All activities in a task are arranged in a stack.
Instance of Activity B
Instance of Activity C
The one that's currently
Instance of Activity B
Instance of Activity A
A Stack
The one that began the task
(typically, an activity the user
selected in the application
• If one activity starts another, the new activity is pushed on
the stack and it becomes the running activity.
• When the user presses the BACK key, the current activity is
popped from the stack and the previous one resumes.
CEG436: Mobile Computing (PM)
• An affinity means a preference for each
activity to belong to a certain task.
• An individual affinity can be set for each
• By default, a new activity is launched into the
task of the activity that called startActivity().
CEG436: Mobile Computing (PM)
• If the Intent object passed to startActivity()
contains the FLAG_ACTIVITY_NEW_TASK flag,
– If there's already an existing task with the same
affinity as the new activity, the activity is launched
into that task.
– If not, it begins a new task.
• allowTaskReparenting == true  it can move
from the task it starts in to the task it has an
affinity for when that task comes to the fore.
CEG436: Mobile Computing (PM)
Launch Modes
standard (default)
• A launch mode can be set for each activity
• The modes differ from each other on four
points …
CEG436: Mobile Computing (PM)
Launch Mode Differences-1
• Which task will hold the activity that responds
to the intent
Original Task
Original Task
New Task
New Activity
Activity A
Activity A
Root Activity
Root Activity
CEG436: Mobile Computing (PM)
New Activity
Launch Mode Differences-2
• Whether there can be multiple instances of
the activity
• A "standard" or "singleTop" activity can be instantiated
many times.
• A "singleTask" or "singleInstance" activity is limited to
just one instance.
Task A
Task B
Task A
Activity B
Activity C
Activity B
Activity A
Activity D
Activity A
Task B
Activity B
Activity C
Activity B and Activity C are
CEG436: Mobile Computing (PM)
Activity C
Activity C is singleTask or
Launch Mode Differences-3
• Whether the instance can have other activities
in its task
CEG436: Mobile Computing (PM)
• These modes permit multiple activities to belong to the
• A "singleTask" activity will always be the root activity of the
• An activity stands alone as the only activity in its task.
Launch Mode Differences-4a
• Whether a new instance of the class will be
launched to handle a new intent
Activity D
Activity D
Activity D
Activity D
Activity C
Activity C
Activity B
Activity B
Activity B
Activity A
Activity A
Activity A
Original Task
If D is"standard"
If D is"singleTop"
Activity C
An intent arrives for
an activity of type D
CEG436: Mobile Computing (PM)
The existing instance
D is expected to
handle the new
intent (since it's at
the top of the stack)
Launch Mode Differences-4b
• Whether a new instance of the class will be
launched to handle a new intent (Cont)
Activity D
Activity C
Activity B
Activity A
An intent arrives for
an activity of type B
The existing instance
B is not expected to
handle the new
intent (since it's not
at the top of the
Original Task
CEG436: Mobile Computing (PM)
Activity B
Activity B
Activity D
Activity D
Activity C
Activity C
Activity B
Activity B
Activity A
Activity A
If B is"standard"
If B is"singleTop"
Launch Mode Differences-4c
• Whether a new instance of the class will be
launched to handle a new intent (Cont)
Activity B
Original Task
CEG436: Mobile Computing (PM)
An intent arrives for
an activity of type B
Activity B
If B is"singleInstance"
A "singleInstance"
activity is always at
the top of the stack,
so it is always in
position to handle
the intent.
Launch Mode Differences-4d
• Whether a new instance of the class will be
launched to handle a new intent (Cont)
Activity B
Activity A
Activity B
An intent arrives for
an activity of type B
Activity A
Original Task
If B is"singleTask"
Activity A
Activity A
Activity B
Original Task
CEG436: Mobile Computing (PM)
An intent arrives for
an activity of type B
Activity B
Activity B can handle
the intent since it is
in position.
Activity B cannot
handle the intent
since it is not in
position and the
intent is dropped.
If B is"singleTask"
Clearing the Stack
• Default Control
– If the user leaves a task for a long time, the system
clears the task of all activities except the root activity.
• If alwaysRetainTaskState is set to the root activity
– The task retains all activities in its stack even after a
long period.
• If clearTaskOnLaunch is set to the root activity
– The stack is cleared down to the root activity
whenever the user leaves the task and returns to it.
– The user always returns to the task in its initial state,
even after a momentary absence.
CEG436: Mobile Computing (PM)
Clearing the Stack
• If finishOnTaskLaunch is set to an activity of a task
– The activity remains part of the task only for the
current session.
– If the user leaves and then returns to the task, it is no
longer present.
• If an intent includes the
FLAG_ACTIVITY_CLEAR_TOP flag and the target
task already has an instance of the type of activity
that should handle the intent in its stack, all
activities above that instance are cleared away.
CEG436: Mobile Computing (PM)
Activity Lifecycle
• Running state: An activity is in the foreground of the
screen (at the top of the activity stack for the current
• Paused state: An activity has lost focus but is still visible
to the user.
• Stopped state: An activity is completely obscured by
another activity.
– It still retains all state and member information.
• If an activity is paused or stopped, the system can drop
it from memory either by:
– asking it to finish (calling its finish() method)
– simply killing its process.
CEG436: Mobile Computing (PM)
Activity Lifecycle
when the system is about to start resuming another
This method is typically used to commit unsaved
changes to persistent data, stop animations and other
things that may be consuming CPU, and so on.
just before the activity starts interacting with the user
At this point, the activity is at the top of the activity
stack, with user input going to it.
after the activity has been stopped, just prior to it
being started again
just before the activity becomes visible to user
when the activity is first created, or
when the activity was killed
when the activity is no longer visible to the user
This may happen because it is being destroyed, or
because another activity has been resumed and is
covering it.
Called before the activity is destroyed
CEG436: Mobile Computing
Activity Lifecycle
• Three nested loops for the entire lifecycle
• Visible Lifetime
– During this time, the user can see the activity on screen
– onStart() and onStop() can be called multiple times, as the
activity alternates between being visible and hidden to the user.
• Foreground Lifetime
– During this time, the activity is in front of all other activities on
screen and is interacting with the user.
CEG436: Mobile Computing (PM)
Saving activity state
CEG436: Mobile Computing (PM)
Service Lifecycle
CEG436: Mobile Computing
Service Lifecycle
• The service is started by calling
– Context.startService()
• Runs until someone, including itself, calls
– Context.stopService()
• Clients establish a connection to the Service
object and use that connection to call into the
– established by Context.bindService()
– closed by Context.unbindService()
CEG436: Mobile Computing (PM)
Broadcast Receiver Lifecycle
• Only single callback method
• onReceive(currentContext, Intent broadcastMsg)
• When a broadcast message arrives for the
receiver, Android calls the method and passes it
the Intent object containing the message.
• A process with an active broadcast receiver is
protected from being killed but a process with
only inactive components can be killed by the
system at any time.
CEG436: Mobile Computing (PM)
Android Location Service
CEG436: Mobile Computing
Determining User Location
• Multitude of location sources GPS, Cell-ID, and Wi-Fi
can each provide a clue to users location. Determining
which to use and trust is a matter of trade-offs in
accuracy, speed, and battery-efficiency.
• User movement Account for movement by reestimating user location every so often.
• Varying accuracy Location estimates coming from each
location source are not consistent in their accuracy. A
location obtained 10 seconds ago from one source
might be more accurate than the newest location from
another or same source.
CEG436: Mobile Computing (PM)
• Address A class representing an Address, i.e, a set
of Strings describing a location.
• Geocoder A class for handling geocoding and
reverse geocoding.
• GpsStatus.NmeaListener Used for receiving
NMEA sentences from the GPS.
• LocationManager This class provides access to
the system location services.
• For more information, read the guide to
Obtaining User Location.
CEG436: Mobile Computing (PM)
• LocationManager lcm = (LocationManager)
• listener = new LocationListener() { … }
• lcm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, a, b,
NETWORK_PROVIDER == cell phone tower and Wi-Fi
a == minimum time interval between notifications; 0 is ok
b == minimum change in distance between notifications; 0 is ok
• public void onLocationChanged(Location ltn) {
// your method
• public void onStatusChanged(String provider, int status, Bundle extras) {…}
• public void onProviderEnabled(String provider) {…}
• public void onProviderDisabled(String provider) {…}
CEG436: Mobile Computing (PM)
Location Use Model for Performance
CEG436: Mobile Computing
Location Trade-Offs
• Long windows of listening for location fixes
can consume a lot of battery power, but short
periods might not allow for sufficient
• locationManager.removeUpdates(listener);
• locationManager.getLastKnownLocation(pro);
• The most recent fix is not always the best.
– Choose location fixes based on several criteria.
CEG436: Mobile Computing (PM)
Tagging content with location
CEG436: Mobile Computing
Help decide where to go
CEG436: Mobile Computing
Providing Mock Location Data
• Eclipse
– Window > Show View > Other > Emulator Control
– Using the Emulator Console send coordinates:
• geo fix -121.45356 46.51119 4392
• geo nmea $GPRMC,…
– Use a GPX file describing a route for playback.
– Use a KML file describing individual place marks.
CEG436: Mobile Computing (PM)
• Geocoder gcd =
new Geocoder( context, Locale. getDefault());
List<Address> addresses =
gcd. getFromLocation(latit, longi, 1);
if (addresses.size() > 0)
CEG436: Mobile Computing (PM)
CEG436: Mobile Computing (PM)
Google Maps External Library
• Set up a new Android project — or reconfigure an existing one — to build
against the installed Google APIs add-on
• Set up an Android Virtual Device configuration that uses a the Google APIs
• Add a uses-library element to your application's manifest file, to reference
the Maps library.
– <uses-library android:name= "" />
• Use the Maps classes in your application
• Get a Maps API Key, so that your application can display data from the
Google Maps service.
• Sign your application properly, using the certificate that matches your API
• Example: <sdk>/add-ons/google_apis-<api-level>/samples/MapsDemo
CEG436: Mobile Computing (PM)
Selected APIs
CEG436: Mobile Computing
• Camera class is used to set image capture
settings, start/stop preview, snap pictures, and
retrieve frames for encoding for video.
• GeomagneticField estimates magnetic field at a
given point on Earth, and to compute the
magnetic declination from true north.
• Sensor Class representing a sensor. SensorEvent
holds information such as the sensor's type, the
time-stamp, accuracy and
sensor's data. SensorManager lets you access the
device's sensors.
CEG436: Mobile Computing (PM)
• BluetoothAdapter Represents the local Bluetooth
radio. Entry-point for all Bluetooth interaction.
Instantiate a BluetoothDevice using a known MAC
address, and create a BluetoothServerSocket.
• BluetoothProfile.ServiceListener An interface for
notifying BluetoothProfile IPC clients when they
have been connected or disconnected to the
• BluetoothSocket A connected or connecting
Bluetooth socket.
CEG436: Mobile Computing (PM)
• NfcManager This is the high level manager,
used to obtain this device's Near Field
Communication (NFC) NfcAdapter. Acquire an
instance: getSystemService(String)
CEG436: Mobile Computing (PM)
• ConnectivityManager Class that answers queries
about the state of network connectivity.
• LocalSocketAddress A UNIX-domain (AF_LOCAL)
socket address.
• NetworkInfo Describes the status of a network
interface of a given type (currently either Mobile
or Wifi).
• Uri.BuilderHelper class for building or
manipulating URI references.
CEG436: Mobile Computing (PM)
• WifiConfigurationA class representing a
configured Wi-Fi network, including the
security configuration.
• WifiManagerThis class provides the primary
API for managing all aspects of Wi-Fi
CEG436: Mobile Computing (PM)
Device Administration
• DeviceAdminReceiver Can interpret raw
intent actions that are sent by the system.
• DevicePolicyManager manages policies for
one or more DeviceAdminReceivers
• DeviceAdminInfo specify metadata for a
device administrator component.
• Device Administration API sample
CEG436: Mobile Computing (PM)
CEG436: Mobile Computing (PM)

similar documents