Topic 2: Android Application Fundamentals
(Authors: Dr Caspar Ryan, Dr Ermyas Abebe, Mr. Keith Foster)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 1
Activities
• An application consists of multiple Activities that are loosely bound/coupled to each other.
• Users interact with Activities to accomplish a specific task e.g. dial the phone, take a photo, send an email, or view a map.
• A user task may be made up of many Activities e.g. i) take a photo ii) edit the photo iii) select recipients iv) email the photo.
• The activity UI (user interface) typically fills a single screen, but may float on top of other window(s) (but there is only ever one foreground activity) ..
• Splitscreen available at OS level in Android 7+
See https://developer.android.com/guide/topics/manifest/activity-element.html for Activity configuration Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 2
Application Fundamentals
Applications are composed of one or more of the following components:
1. Activity: The primary executable component of an application:
• typically associated with a single screen user interface (UI)*
• contains widgets based on View elements (Button, List etc.).
• extends android.app.Activity or one of its subclasses.
• * Can contain Fragments (android.app.Fragment), a separate
UI sub component (covered in detail later in semester)
• Android 24+ supports split screen at the OS level
2. Task: A conceptual construct (i.e. not represented by Java classes) involving a sequence of activities a user follows to accomplish a specific application task.
• Activities in one task may come from many applications!
• e.g. send message with attachment from another app (photo etc.)
• supported by the Android OS Activity Stack (Back Stack).
• NOTE: Stack=LIFO structure (Last in First Out).
Semester 1, 2019 COSC2309/2347 Mobile Application Development
Topic 2, Slide 3
1. Activity 6. Intent 1. Activity 6. Intent
Task and Activity Stack
DEMO
1. Activity
COSC2309/2347 Mobile Application Development
Application Fundamentals
3. Service: A service is a component that runs in the background (without a UI) to perform long-running or independent operations.
• extends android.app.Service or one of its subclasses.
• can operate independently of the application that started them or
can send/receive data via inter process communication (IPC).
4. Content Provider: A content provider manages a shared set of data and
makes it available to different applications.
• e.g. audio, video, images, personal contact information etc.
• extends android.content.ContentProvider
• Applications can create their own customised Content Providers or
add data to existing ones
• device Contacts are accessed through a ContentProvider
(https://developer.android.com/guide/topics/providers/contacts- provider.html)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 5
Application Fundamentals
5.
Broadcast Receiver: A broadcast receiver is a component that responds to broadcast announcements
• May originate outside the application (e.g. from the system or other apps e.g. incoming phone call)
• Context.sendBroadCast(Intent, …) or Context.sendOrderedBroadcast(Intent, …)
• Can use permissions to limit who receives the broadcast e.g. app must have android.permission.READ_PHONE_STATE to listen for incoming calls
• Use LocalBroadcastManager for local (single app) “broadcasts”
• Is a “light” component that does not perform its own work but initiates other
components or displays alerts such as status bar notifications, Toasts etc.
• Extends android.content.BroadcastReceiver
• Override BroadcastReceiver.onReceive(Context context, Intent intent) tohandlethebroadcastevent
• Add
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 6
BroadcastReceiver contd.
• Implicit broadcasts are system wide broadcasts that are not specific to a single application
https://developer.android.com/about/versions/oreo/background#broadcasts
• As of Android 8.0 (API 26) implicit broadcasts cannot be registered in the Manifest but must be added manually with Context.registerReceiver()
• See example below for Network Broadcast Receiver
// see https://developer.android.com/guide/components/broadcasts // as of API 24 manifest is not sufficient
IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(networkReceiver, filter);
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 7
Application Fundamentals
6. Intent: Three of the core application components (Activities, Services, and Broadcast Receivers) are activated (sequenced) through messages called Intents.
• Allows for loose coupling between applications with Activities being the most common target of an Intent.
• Instances of android.content.Intent
• Each activity declares the intents it can handle in the application
manifest
• e.g. Dialing a number by invoking an intent
Intent intentToDial = new Intent(Intent.ACTION_DIAL,
uri.parse(“tel:99252000”));
startActivity(intentToDial);
• NOTE: You cannot launch a Fragment with an Intent. You must host it in an Activity if you wish to do this
https://developer.android.com/guide/components/intents-filters.html
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 8
Intents (android.content.Intent)
Intents encapsulate the following information:
• Component Name (optional): the explicit class name of the component which should handle the event. Can be determined automatically from other fields (e.g. Action)
• Action: A string naming the action to be performed (implicit intent). The OS chooses the appropriate target or delegates the choice to the user. Choose from built in or custom actions. (e.g. Intent.ACTION_DIAL)
• generally the Action dictates how the rest of the fields (data, extras, flags etc.) are structured in the same way a method call has a particular parameter list
• see android.content.Intent API documentation for constants which define the standard actions e.g. Intent.ACTION_DIAL or Intent.ACTION_SEARCH
• https://developer.android.com/guide/components/intents- common.html
• Data: URI [Intent.setData(Uri data)] and MIME type [Intent.setType(String type)] of the data to be acted on. Dependent on the chosen Component or Action. (e.g. “tel:9925 1234”)
• NOTE: See constants in android.content.Intent for full list of built in Intents Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 9
Intents (Contd.)
• Category: A string containing additional information about the kind of component that should handle the intent. (e.g. Intent.CATEGORY_BROWSABLE)
• Extras: Extra parameter information as Key-value pairs (e.g. Intent.ACTION_TIMEZONE_CHANGED intent has a “time-zone” extra to identify new time zone. As with data, is action or component specific.
• Flags: Flags to the Android system. Defined in the Intent class.
• see FLAG_ constants
• describes flags which effect back stack behaviour and attributes for
• NOTE: Intent Filtering to implicitly choose (i.e. resolve) the target component of an implicit Intent uses only Action, Category and Data (both URI and MIME Type)
• See https://developer.android.com/guide/components/intents-filters.html for more detail on Intents and Intent Filters
• See Intent constructors and methods in API docs
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 10
movie1
1. Activity 6. Intent 1. Activity
Activities and Intents
CODE
6. Intent
1. Activity
Activity
Controller
Activity
movie1
Model
m
ovie2
movie4
1. Activity
Fragment
6. Intent
1. Activity
2. Task
3. Service
6. Intent
1. Activity
Layout
Layout
movie3
of an Android Application
Intent Intent
View
Anatomy
4. Content Provider
5. Broadcast Receiver
COSC2309/2347 Mobile Application Development
Semester 1, 2019 COSC2309/2347 Mobile Application Development
12
Launching Activities
• Designating a launch activity in the application manifest file (required). This “main” activity serves as the application entry point or home screen for launching other activities.
• Start an application specific activity by calling Activity.startActivity with an Intent parameter that explicitly describes the activity
startActivity(new Intent(getApplicationContext(), SignInActivity.class));
• Start an implicit activity provided by another application (user may
chose from many)
Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, recipientArray); startActivity(intent);
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 13
Launching Activities
• Call Activity.startActivityForResult(…) (instead of Activity.startActivity(…)) and implement the Activity.onActivityResult(…) callback method to receive returned data from the activity [via an Intent parameter passed to setResult(int resultCode, Intent data)] *
• * Must call setResult() in destination activity before the Activity.finish() is called e.g. when back button is pressed:
– override finish()
– do some processing
– call setResult()
– call super.finish()
• Your application’s activities can be launched by other applications if you provide an intent filter in the application manifest file
• http://www.openintents.org/ maintains a registry of Intents for cross application usage
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 14
Activities contd.
• Activities can have their own label and icon but use those of the application by default
• Activities must be registered in AndroidManifest.xml within the
• The activity name should be a fully qualified class name (such as, com.example.project.ExtracurricularActivity). However, if the first character of the name is a period (e.g. .ExtracurricularActivity, it is appended to the package name specified in the
• Activities must be defined as a Java class of type android.app.Activity in the application package (as defined in
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 15
Activity Lifecycle
• An activity undergoes many state transitions during the life of an application as it participates in one or more tasks
• Activities are notified of state changes via its callback methods (see next slide) e.g. Activity.onStart(), Activity.onStop() etc.
• These lifecycle methods are responsible for performing application specific tasks (e.g. creating or releasing resources, starting/stopping worker threads, opening/closing files/databases/network connections etc.)
• The lifecycle is closely related to the activity back stack since activities are added and removed as a direct consequence of lifecycle changes (which are directed either by the application, the system or the user)
• Lifecycle management can be delegated to other components, see https://developer.android.com/topic/libraries/architecture/lifecycle.html (not needed for this course)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 16
Activity Lifecycle
Semester 1, 2019
Lifecycle methods take the form
onStateTransition() e.g.
Activity.onResume() or Activity.onPaused()
Three Main states:
Resumed (running)ActivityisinForeground
Paused Activity visible but not in foreground. Retains all state information.
Can be killed by system during extreme memory constraint
Stopped Activity in background. Retains all state information.
App in this state can be destroyed by system if memory required by other activities
Source: https://developer.android.com/guide/components/activities/activity-lifecycle.html
COSC2309/2347 Mobile Application Development Topic 2, Slide 17
Activity Lifecycle (cont.)
Three Lifetimes:
1. Entire
• Create to destroy
2. Visible
• Start to finish
1. Foreground
• Resume to pause
* From Android Studio Development Fundamentals by Neil Smyth
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 18
Activity Lifecycle contd.
• Transitioning to a new activity using an Intent calls onPause() on the old activity, onCreate()/onStart()/onResume() on the new activity and then onStop() on the old activity
– the old activity is placed on the back stack
• Call Activity.finish() to close current activity and go back to previous
– pauses current activity, restarts previous activity [onRestart()/onStart()/onResume()] then stops and destroys current activity
– removed from the back stack
– by default if you instead explicitly transition to the previous activity using an intent, a new instance is created and the current activity is pushed onto the back stack i.e. causes a different set of transitions and back stack states
– https://developer.android.com/guide/components/tasks-and-back- stack.html has further details on the back stack
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 19
Activity Lifecycle contd.
• The back button (triangle) has the same effect as calling finish() i.e. the current activity is destroyed and popped off the back stack
• The home button (circle) causes the current activity to stop and when transitioning back to that activity it goes through restart, start and resume
– the back stack for the task/application remains intact
• The off/standby/power and end call buttons cause the application to
transitionthroughonPause()andonResume() (versiondependent)
• When the background activity remains visible (e.g. the new activity has theandroid:theme=”@android:style/Theme.Dialog” attribute) the calling (background) activity goes through onPause()/onResume() insteadofonStop()/onStart()
• NOTE: The back stack is per-task or application specific (i.e. not system wide)
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 20
Activity Lifecycle contd.
• Ongoing tasks related specifically to the current activity should be handled in onPause() and onResume()
– e.g. any data that the user has entered or modified in the current activity should be saved and resumed here (even though the system maintains UI state such as data entered in text fields, scroll position etc.)
– any processing or visual representations related to the current activity should be stopped and started here e.g. animation, playing a video etc.
• Actions that are resource intensive or time consuming (such as retrieving datafromtheweb)shouldbehandledinonCreate() oronStart() so that they are not performed so frequently
– local caching can help here, covered in a later lecture
– saving in onStop() rather than onPause() speeds transition to next Activity
• IMPORTANT: there is no guarantee that onPause(), onStop() or onDestroy() willbecalled
– catastrophic failure e.g. application force close or battery depletion/device reset
• NOTE: In API < 15 critical application state should be saved in onPause()
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 21
Activity Lifecycle contd.
• There is an additional state/lifecycle related method Activity.onSaveInstanceState(Bundle outState)
• This method is called only when an activity is killed by the system to reclaim resources outside of normal operation
• The Bundle can be retrieved and reused to restore transient (e.g UI related) state during onCreate() or onRestoreInstanceState()
– assumes that data is small, serializable and can be contained in a Bundle instance
• note that the default Activity.onSaveInstanceState() saves and
restores intermediate UI state such as data entered into a text field, selection state of widgets etc.
– this is often sufficient and does not need to be over ridden
– If you override then generally will call the default (super) implementation
• onPause() can be a better alternative (since it is always called) unless your persistence implementation is too heavyweight for something like UI rotation which happens frequently
• see Topic5 RotationAsyncActivity.java for how this can be handled using Activity.onRetainNonConfigurationInstance() or the newer Fragment.setRetainInstance(boolean) method
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 22
Fragment Lifecycle
from https://developer.android.com/guide/components/fragments Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 8, Slide 23
Android Resources
res/*
aapt tool
R.java
All resources are stored in /res folder in strictly organized hierarchy
• res/values/: store values like string resources,
style resources etc. (button text, activity title etc.)
• res/layouts/: store XML UI layout of application
components
• res/anim/ : tween animations
• res/drawable/: frame animations, graphics etc.
• res/raw/: other files, .mp3, binary or text files
required by your app
R.java is auto-generated class providing access to these resources e.g. R.layout.main (to access res/layouts/main.xml)
• See packages view in Android Studio and Project
View->build->generated->not_namespace…
Tools compile all sources and resources into a single Android Package File (.apk), which is deployed to a device . 1.apk == 1 application == 1 process
.java
.class
.dex
.apk
dx tool
apk builder
Semester 1, 2019
COSC2309/2347 Mobile Application Development Topic 2, Slide 24
Context
• Activity extends android.app.Context
• application scope storage
• Context.getResources() to get bundled resources and assets such as strings, icons etc.
• Context.getSharedPreferences(…) to retrieve application preferences
• Generic application functionality such as application specific file, directory, database management etc.
• Application permission management
• Context.getSystemService() to Access system level
services e.g. location, search or wi-fi services
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 25
Application Resources
• Android encourages separating resources from application code
• i.e. Strings, labels, icons, images, layouts etc. are defined and stored independently of your .java source files
• Code is less cluttered and easier to read
• Resources organised by type and easier to manage
• Encourages easy localisation, customisation, individual preferences etc.
• Resources can be accessed from .java source as well as other .xml resource files e.g. mylayout.xml refers to strings in strings.xml
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 26
Application Resources (contd.)
• Resource filenames and labels must be unique, lowercase, containing letters, numbers, underscores and periods
• Resource attributes follow standard identifier naming conventions (but following filename conventions makes them easier to identify in code)
• Resources are referenced programmatically via the R.java fileinthe/generated directorywhichisupdatedeachtime resources change
• Programmatic access using android.content.Context.getResources()(accessible through Activity subclass) e.g. getResources.getString(R.string.hello);
• Resource file access using @[resource type]/[resource name] e.g.@string/hello
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 27
System Resources
• Systemresourcescanbeusedwheresuitableinstead of defining your own (for platform consistent look and feel)
• Programmaticaccesse.g. getResources.getString(android.R.string.ok);
– note that android is a package, R is a class, string is a static inner class and ok is an attribute
–Seeandroid.R.* APIforfulllistofattributes
• Resourcefileaccessusing@android:[resource
type]/[resource name] e.g. @android:string/ok
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 28
Simple Resources (values)
•
•
•
Strings
– Convention is /res/values/string.xml but can have arbitrary filenames
– Simplifies internationalisation/localisation (e.g. language translation)
– @string/xyz or getResources().getString(R.string.xyz);
–
Colours
– Convention is /res/values/colors.xml
– Simplifies accessibility e.g. visual impairment and customisation e.g. user preference
– #RGB, #ARGB, #RRGGBB, #AARRGGBB where A=alpha, RGB=red green blue, and each A R G or B is a 4 bit hex digit 0-F e.g. #00F is a 12 bit colour (blue)
– @color/xyz or getResources().getColor(R.color.xyz);
–
– Convention is /res/values/dimensions.xml
– Simplifies porting to different devices e.g. tablet versus smartphone
– Units of measurement: px=pixels, in=inches, mm=millimetres, pt=point, dp=density independent pixels, sp=scale independent pixels
– @dimen/xyz or getResources().getDimension(R.dimen.xyz);
–
– NOTE: Only contains one value, use multiple dimension entries e.g. for width and height
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 29
Layout Resources
• Layouts are defined declaratively in .xml files – /res/layout directory
• Usually associated with a single activity or fragment but can be shared among many activities
• May also have separate layout files for different parts of a single UI
– i.e. can be nested to improve modularity
• Layouts may also be manipulated programmatically
– reduces code readability
• Android Studio provides UI support for designing layouts
– Goodforbasiclayouts(butcanhelpunderstandingtoprogram manually)
– May need to edit .xml directly for advanced layout
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 30
Other Resources
• XML files
– /res/xml/xyz.xml
– Use inbuilt xml processing to handle declarative data
– XmlResourceParser parser=getResources().getXml(R.xml.xyz);
• Raw files
– /res/raw/xyz.xml
– Use arbitrary file types not supported by inbuilt resource handling
– InputStream is=getResources().openRawResource(R.raw.xyz);
• Assets
– /assets/xyz.xyz
– Use arbitrary file types but don’t treat them as resources
– Not included in R.java
– Accessed through the android.content.res.AssetManager class [e.g. final InputStream open(String fileName)]
• Others
– String arrays, menus, animations, drawables, styles, custom layout etc.
– See https://developer.android.com/guide/topics/resources/available-resources.html
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 31
Manifest and Permissions
AndroidManifest .xml File: All application components (Activities, Services etc.) are declared in this manifest file. In addition the following are also declared:
• permissions required by the application (send sms, access internet , dial phone etc.)
• see class android.Manifest.permission constants in API docs
• NOTE: the constant String value is used for android:name in the Manifest
• hardware and software features the application requires
Activity Declaration
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 32
Internet permissions
Runtime Permissions (API 23+)
• In Android 6.0+ (API level 23+), permissions are requested at run-time
– users can grant/revoke permissions at any time
– requires setting targetSdkVersion to 23 or higher (covered later)
– be wise/safe and only allow what you need to!
– some permissions are granted automatically from the manifest (Normal Permissions)
– some permission are granted if the app is signed with a valid certificate (Signature Permissions)
– some permissions can only be granted at runtime and must be requested every time the app is run (Dangerous permissions)
– See the following for a list of the different permission types
– https://developer.android.com/guide/topics/permissions/overview#normal-
dangerous
– See the following on how to code the permission requests
– https://developer.android.com/training/permissions/requesting#java
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 33
Manifest Permissions
• Older versions (Android 5.1 (API level 22) and below) require ALL permissions to be granted once when the app is installed
– eveniftheuserdoesnotintendtousethosefeatures
– you must accept all features or can’t use the app!
– leads to unnecessary permission creep and data mining
– e.g.whydoesmyweatherappneedtoknowallmycontactsdetails!
– adb shell pm list permissions
available for developers to inspect a specific platform
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 34
Gradle Build System
• Gradle is a build system based on the Groovy language
• https://gradle.org/ (general info about Gradle)
• https://developer.android.com/studio/build/index.html (main reference for Android)
• In Android Studio a Project can have many modules, where a module can be a separate application
– There is a gradle file for both the project itself and each module
• Android has its own plugin to wrap Gradle functionality specifically for Android builds (either within Android Studio or cmd line)
– specified in the project gradle file or AS Project Structure->Project dialog
– The gradle plugin version specifies which version of the build tools are used unless explicitly
overridden in a module gradle file
• To get started you can perform simple builds without looking at the specifics of the gradle system
• we will cover adding support libraries in next weeks lecture
• https://developer.android.com/studio/run/index.html
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 35
Semester 1, 2019 COSC2309/2347 Mobile Application Development Topic 2, Slide 36
From: https://developer.android.com/studio/build/index.html