ANDROID
PROGRAMMING
-INTRODUCTION
Introduction
• Android is built on top of more than 100 open projects,
including linux kernel
• To increase security, each application runs with a distinct
system identity (linux UID and GID)
• Application are isolated from each other
• Application are isolated from each other
• Use a quite efficient IPC mechanism
• To facilitate resource access from isolated application,
android exploit a permission-based security mechanism
• Each application needs permissions to access system resources • Permissions are granted at application installation time
Android architecture
Kernel Linux Set of drivers
The kernel provides preemptive multitasking,low level core system services, like
Android architecture
Dalvik VM Specific Libraries This is a set of libraries used predominantly for interacting directly with an instance of the Dalvik VM and is unlikely to be used by most Android
application developers.
• Dalvik VM: similar to the JVM • Designed by Google
more efficient than JVM in terms of memory usage, designed to
run under resource constraints • Act as a sandbox: each
application runs inside a DVM
Android SW libraries (native language)
Surface Manager: Rendering of Views 2D graphics
Media Framework:
Manage different codec, e.g. mp3,H.264,MPEG4,etc. Rendering of Font types In process DB Open GL ES 2D and 3D graphics For Embedded systems
Web engine
C standard library
Android architecture
Application framework: Set of managers
wrapping the native libraries, make them accessible to the programmer as API
Android libraries
• android.app – Provides access to the application model and is the cornerstone of all Android applications.
• android.content – Facilitates content access, publishing and messaging between applications and application components.
• android.database – Used to access data published by content providers and includes SQLite database management classes.
• android.graphics – A low-level 2D graphics drawing API including colors, points, filters, rectangles and canvases.
• android.hardware – Presents an API providing access to hardware such as the accelerometer and light sensor.
• android.opengl – A Java interface to the OpenGL ES 3D graphics rendering API. • android.opengl – A Java interface to the OpenGL ES 3D graphics rendering API.
• android.os – Provides applications with access to standard operating system services including messages, system services and inter-process communication.
• android.media – Provides classes to enable playback of audio and video.
• android.net – A set of APIs providing access to the network stack. Includes android.net.wifi, which provides access to the device’s wireless stack.
• android.provider – A set of convenience classes that provide access to standard Android content provider databases such as those maintained by the calendar and contact applications.
• android.text – Used to render and manipulate text on a device display.
• android.util – A set of utility classes for performing tasks such as string and number conversion, XML handling and date and time manipulation.
• android.view – The fundamental building blocks of application user interfaces.
• android.widget - A rich collection of pre-built user interface components such as buttons, labels, list views, layout managers, radio buttons etc.
Android frameworks (not complete list)
• Activity Manager – Controls all aspects of the application lifecycle and activity stack.
• Content Providers – Allows applications to publish and share data with other applications.
• Resource Manager – Provides access to non-code embedded resources such as strings,
color settings and user interface layouts.
• Notifications Manager – Allows applications to display alerts and notifications to the user.
• View System – An extensible set of views used to create application user interfaces.
• Package Manager – The system by which applications are able to find out information about
other applications currently installed on the device.
• Telephony Manager – Provides information to the application about the telelphony services
available on the device such as status and subscriber information.
• Location Manager – Provides access to the location services allowing an application to
Android architecture
Security
•
Security goals
• Protect sensible data of users, like contact and e-mail • Protect system resources
• Protect an application from other applications
•
Security mechanisms
•Security mechanisms
• Native mechanisms, at kernel level
• Sandboxing, each application runs inside a sandbox
• Limited access to system resources. Resources restricted via permissions
• Secure IPC
• Application signature via a certificate
Sandbox and permission
Sandbox: Linux UID=1234 Application: UID 1234 DVM DVM R e so u rce s camera android.permission.CAMERA <uses-permission> …. http://source.android.com/devices/tech/security/#the-application-sandbox
Sandbox and permission
• Sandbox provides access to a limited number of system
resources
• The access to a resosource is restricted using a
permission
• User should declare the use of the permission in the
• User should declare the use of the permission in the
manifest file and grant (all) permissions at installation time
• Sandboxing prevents one app from being able to read
data or modify the code of other apps installed on the system.
• This feature helps to contain malware and other security threats, so
that even if a vulnerable app is cracked via an exploit (or a
malicious app manages to get itself installed on a device), it can't be used to gain further access to other software or data stored on the device.
Sandbox and permission
•
Different applications can run in the same
process.
•
For this approach, one first must sign those
applications using the same private key and you
applications using the same private key and you
then must assign to them the same Linux user ID
using the manifest file, by defining the manifest
attribute android:sharedUserId with the same
value/name.
Sandobox and permission
Sandbox: Linux UID=1234 Application: UID 1234 DVM Application: UID 1234 DVM DVM R e so u rce camera DVM
Activity,Services and permission
• An activity can be launched by another sw component
• For this to occur, the activity defines an Intent Filter
• The component lunches an implicit intent matching the filter
• In order to make the activity ‘private’ to the application (sw
components defined in the manifest file), use components defined in the manifest file), use
android:exported=false
Brodcast receiver and permission
• By default, receivers are exported and can be invoked by
any other application.
• To restrict application that can send an Intent to a
broadcast receiver set appropriately the <receive> tag
• The intent is not delivered to the BroadcastReceiver • The intent is not delivered to the BroadcastReceiver
• No security exception in case of violation, only a log message
Whether or not the broadcast receiver can receive messages from sources outside its application
Content Provider
• By default, they are ‘public’
• android:exported=false (make it private)
• Two kinds of permissions
• android:readPermission • android:writePermission • android:writePermission
Storing data:
How to save data on a device
• Using internal storage
• By default, accessible only to owner of the application • Possible to encrypt data
• Using external storage (e.g., SD card)
• Memory is globally readble and writable • Memory is globally readble and writable
• Do not store executable,class file or sensitive information
• SD Card can be removed
• Exploit user validation
• Using content providers
Using networking
• Similar to Linux networking
• Use HTTPS (HttpsURLConnection class) • Use SSL (SSL Socket class)
• Do not trust response (input validation)
• Using SMS
• Using SMS
• SMS is neither encrypted nor strongly authenticated on either the
network or the device.
Using WebView
• Consumes web content that can include HTML and
JavaScript
• Code Inejction
• setJavaScriptEnabled() • addJavaScriptInterface() • addJavaScriptInterface()
Cryptography
• Support full-filesystem encryption
• provide secure communications channels
• A set of cryptographic APIs for use by applications.
Characteristics of android applications
• User interaction
• touch screen based UI interface
• Variable screen size
• From low, medium, high (smart TV)
• Resource
• Resource
• usage is an issue
• …but..
• Sensors
• Position, orientation, magnetic field, light sensor, ..
• Portable
• Context-awareness based applications (what’s around me, where
Bird’s eye view to application architecture
User Interface • Activity • Fragment
UI runs in a thread
Main thread it should respond fast
responsiveness
Computation
• Service
• Broadcast receiver
• Separate thread
• Need mechanism to interact with UI • Implements the “business logic”
Data • Preference • File • SQLite • Network • Content provider
What an application is composed of?
SW component Resources apk + …. Resources apk Manifest FileWhat an application is composed of?
• Software components
• Activity
• Fragment
• Service
• Broadcast receiverBroadcast receiver • Content provider • Intent
• Resources
• Pictures, video, audio file, etc.
• Accessed via an ID
Android applications
• Every application runs in its own linux process (receivers
its own User ID)
• A process is created when a component of the application
needs to be run needs to be run
• An unusual feature of Android is that an application
process’s lifetime is not directly controlled by the application (more on this soon)
• For example, if the application is temporary not visible the system
Software components - activity
• The simplest application is composed of
a single activity that ‘inflates’ a UI, defined by an XML file (some similarity with
HTML)
• An activity is an event-triggered software
User Interface
• An activity is an event-triggered software
component staying behind a UI and managed by the operating system via callbacks or hooks
• It also reacts to user generated events
coming from UI via handlers (e.g., push a button)
Software components -activity
• The response time of an activity should be
small (<5s) otherwise the ANR message appears
• Multithreading is required to do slow work in
background User Interface Activity background Activity
Software components - activity
• An Activity has a state, {running , paused, stop}
• The system can kill an activity in the pause or stop state
to reclaim resources
• To assure consistency when a killed activity restarts, user
may implement callback methods to manage the may implement callback methods to manage the information that must persist
• These methods are called before killing or restarting the
activity
RUNNING STOP
KILLED
Demo
• Download SDK, develop by line commands
My first application
Target API Lowest API level
… from here, accept all the default options Lowest API level
My first application
onCreate: Called when the activity is starting. setContentView(): inflates the ‘layout’ inflates the ‘layout’
My first application
string.xml
My first applicaition
My first application
Software components - activity
User Interface
User Interface
• Usually, inside an application one activity is ‘marked’ as
MAIN (in the manifest file) and launched when a user touches the launching icon in the Home screen Activities
• However, an activity A can start another activity B
Software components - Intent
User Interface User Interface Matching Filter• The activity can start another activity using a mechanism
based on Intent and Filters
• An intent is a message directed either explicitly to another
activity (by class name), or implicitly to any activity whose
filter matches the intent’s action and data
Software components - Intent
User Interface User Interface Matching Filter• An Intent contains in fact the action to be performed and
optionally data upon which to work
• The task of finding the right activity that can perform the
action is called intent resolution
Broadcast intent
• System wide intent received by special component named
broadcast receivers that has been registered with the intent • Low battery • Chage in connectivity • Chage in connectivity • Etc.. • Asynchronous transmission • Ordered transmission
• in that it is sent to one receiver at a time where it can be processed
and then either aborted or allowed to be passed to the next Broadcast Receiver.
Broadcast receiver
• Broadcast Receivers are the mechanism by which applications
are able to respond to Broadcast Intents.
• A Broadcast Receiver must be registered by an application and
configured with an Intent Filter to indicate the types of broadcast in which it is interested.
• When a matching intent is broadcast, the receiver will be
invoked by the Android runtime regardless of whether the application that registered the receiver is currently running.
• The receiver then has 5 seconds in which to complete any
tasks required of it (such as launching a Service, making data updates or issuing a notification to the user) before returning.
• Broadcast Receivers operate in the background and do not
Software comp – broadcast receiver
• No UI
• Receive and react to
broadcast announcement, or broadcast intents Filter Broadcast intent or broadcast intents • BOOT_COMPLETED • ..
• It may start an activity, a
service, or it may use the notification service to alert the user
Broadcast receiver
Services
• Android Services are processes that run in the
background and do not have a user interface.
• They can be started and subsequently managed from
Activities, Broadcast Receivers or other Services. Activities, Broadcast Receivers or other Services.
• Android Services are ideal for situations where an
application needs to continue performing tasks but does not necessarily need a user interface to be visible to the user.
Services
• Although Services lack a user interface, they can still notify the user
of events through the use of notifications and toasts (small notification messages that appear on the screen without interrupting the currently visible Activity) and are also able to issue Intents.
• Services are given a higher priority by the Android runtime than many
other processes and will only be terminated as a last resort by the other processes and will only be terminated as a last resort by the system in order to free up resources.
• In the event that the runtime does need to kill a Service, however, it
will be automatically restarted as soon as adequate resources once again become available.
• Example situations where a Service might be a practical solution
include the streaming of audio that should continue when the
application is no longer active, or a stock market tracking application that needs to notify the user when a share hits a specified price.
Software components - service
• A service runs in
background and has not a UI
• Used to perform a
long-running operation or to supply functionality for User
Interface
supply functionality for other applications to use.
• Activated explicitly, or via
the intent/filter mechanism
• Can issue intents,
notifications, or Toast message
Activity
Software components: Service
• System-level service
• WINDOW_SERVICE
• The top-level window manager
• LOCATION_SERVICE
• controlling location (e.g., GPS) updates • controlling location (e.g., GPS) updates
• CONNECTIVITY_SERVICE
• Handling management of network connections • ….
• User defined
• Intent Service (execute inside its own thread and dies) • Started Service
Notification
• A service, running in the background, needs a way to let
users know something of interest has occurred, such as when email has been received.
• Moreover, the service may need some way to steer the
• Moreover, the service may need some way to steer the
user to an activity where they can act upon the event – reading a received message, for example.
• For this, Android supplies status bar icons, flashing lights,
Software comp – content provider
•
The content provider is the data tier for Android
applications
•
Android ships with many content providers
• File — Stores data such as browser bookmarks
• Contacts — Stores user contacts
• Contacts — Stores user contacts
• SQLite db • … SQLite File CONTENT PROVIDER Remot e Data store Activity
Content providers
• Content Providers implement a mechanism for the sharing of
data between applications.
• Any application can provide other applications with access to
its underlying data through the implementation of a Content
Provider including the ability to add, remove and query the data (subject to permissions).
(subject to permissions).
• Access to the data is provided via a Universal Resource
Identifier (URI) defined by the Content Provider. Data can be shared in the form a file or an entire SQLite database.
• The native Android applications include a number of standard
Content Providers allowing applications to access data such as contacts and media files.
• The Content Providers currently available on an Android
Resources
• XML files defining:
• Layout (by tar the most important resource) • String • String array • Integer array • Integer array • Color • Styles…
• Binary image file (icon.png)
• Stored in the /res/ directory
• Accessed from the code through a symbolic ID
• The mapping resource symbolic ID and resource is done
Assets
• Accessed via an Asset Manager
• Files that maintain their original raw format
Context
• When an application is compiled, a class named R is
created that contains references to the application resources.
• The application manifest file and these resources
combine to create what is known as the Application combine to create what is known as the Application
Context.
• This context, represented by the Android Context class,
may be used in the application code to gain access to the application resources at runtime.
• In addition, a wide range of methods may be called on an
application’s context to gather information and make changes to the application’s environment at runtime.