mobile application development – android –lecture 2€¦ · android –lecture 2 mtat.03.262...
TRANSCRIPT
Mobile Application Development –
Android – Lecture 2Android – Lecture 2
MTAT.03.262
Satish [email protected]
Android Lecture 1- recap
• What is Android
• How to develop Android applications
• Constructing the UI
– Resources– Resources
– Views & Layouts
– Adapters
– Events
• Run, debug & test the applications
11/24/2011 Satish Srirama 2/55
Outline
• Basic application components
• Location based services
• Mobile Cloud research
11/24/2011 Satish Srirama 3/55
Basic Application Components
• Activities
– UI component
– Typically corresponding to one screen.
• BroadcastReceivers
– Respond to broadcast Intents.
• Services
– Faceless tasks that run in the background.
• ContentProviders
– Enable applications to share data.
11/24/2011 Satish Srirama 4/55
Activities
• Typically correspond to one screen in a UI
• But, they can:
– be faceless
– be in a floating window– be in a floating window
– return a value
• For more info
http://developer.android.com/guide/topics/fu
ndamentals/activities.html
11/24/2011 Satish Srirama 5/55
Intents
• Unique concept in Android
• Mobile applications mostly run in their sandboxes
• Applications are isolated from each other
• Intents support interactions among the application componentsapplication components– Components can be of any application in the device
– Android does not distinguish third party applications and native applications
• Activities, services, and broadcast receivers — are all activated through Intent messages
11/24/2011 Satish Srirama 6/55
Working with Intents
• Declare your intention that an Activity or
Service be started to perform an action
• Broadcast that an event/action has occurred
• System matches Intent with Activity that can • System matches Intent with Activity that can
best provide that service
• Activities and BroadcastReceivers describe
what Intents they can service in their
IntentFilters (via AndroidManifest.xml)
11/24/2011 Satish Srirama 7/55
Using intents to launch activities
• Explicitly starting new ActivitiesIntent intent = new Intent(this, MyOtherActivity.class);
startActivity(intent);
• The new activity is started and no connection with the current activity
• The new activity is started and no connection with the current activity
• To get the response back from the sub-Activityprivate static final int SHOW_SUBACTIVITY = 1;
StartActivityForResult(intent, SHOW_SUBACTIVITY);
• The response is sent back assetResult(Activity.RESULT_OK, resultIntent);
11/24/2011 Satish Srirama 8/55
Intent Object
• Contains information of interest to the component that receives the intent
– Action to be taken
• ACTION_CALL - Initiate a phone call
• ACTION_BATTERY_LOW - A warning that the battery is low• ACTION_BATTERY_LOW - A warning that the battery is low
– The URI of the data to be acted on• Uri uri = Uri.parse(“content://contact/people”);
• plus information of interest to the Android system
– Category of component that should handle the intent
• CATEGORY_BROWSABLE - The target activity can safely be invoked by the browser
11/24/2011 Satish Srirama 9/55
Implicit intents and late runtime
binding
• The implicit Intents are mentioned in the
Android Manifest file
11/24/2011 Satish Srirama 10/55
Intent resolution in Android
• Android puts together a list of Intent Filters
• Input Filters that do not match the action or
category are removed from the list
• Each part of the Intent’s data URI is compared • Each part of the Intent’s data URI is compared
to the Intent Filters data tag
• If more than one component is resolved, they
are offered to the user to select
11/24/2011 Satish Srirama 11/55
BroadcastReceivers
• Used for system level message-passing
mechanism
• Components designed to respond to
broadcast Intentsbroadcast Intents
• Think of them as a way to respond to external
notifications or alarms
• Applications can invent and broadcast their
own Intents as well
11/24/2011 Satish Srirama 12/55
Using BroadcastReceivers
• Intent intent = new Intent(NEW_LIFEFORM_DETECTED)
intent.putExtra(“lifeformName”, lifeformType);
intent.putExtra(“longitute”, cuttentLongitude);
Intent.putExtra(“latitude”, cuttentLatitude);
sendBroadcast(intent);
• public class LifeformDetectedBroadcastReceiver extends • public class LifeformDetectedBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent)
{ Uri data = intent.getData();
String type = intent.getStringExtra(“lifeformName”);
…
}
}
11/24/2011 Satish Srirama 13/55
Using BroadcastReceivers - continued
• Register the BroadcastReceiver in manifest
11/24/2011 Satish Srirama 14/55
Content Providers
• Enables sharing of data across applications
– Examples: address book, photo gallery, etc.
• Provides uniform APIs for:
– querying (returns a Cursor)– querying (returns a Cursor)
– delete, update, and insert rows
• Content is represented by URI and MIME type
11/24/2011 Satish Srirama 15/55
Content Provider Basics
• All content providers implement a common interface for querying the provider and returning results– Also support adding, altering, and deleting data
• ContentResolver object from the application context provides access to the content provider– ContentResolver cr = getContentResolver();– ContentResolver cr = getContentResolver();
• Content providers expose their data as a simple table on a database model– Each row is a record and each column is data of a particular type
and meaning
– Every record includes a numeric _ID field that uniquely identifies the record within the table
11/24/2011 Satish Srirama 16/55
URIs of Content Providers
• Each content provider exposes a public URI
• A content provider that controls multiple tables exposes a separate URI for each one
• Example:
• <provider android:name=".TransportationProvider"android:authorities="com.example.transportatio
nprovider". . . >
11/24/2011 Satish Srirama
http://developer.android.com/guide/topics/providers/content-providers.html
17/55
Querying a Content Provider
• To query a content provider you need
– The URI that identifies the provider
– The names of the data fields you want to receive
– The data types for those fields
• The querying returns a object• The querying returns a Cursor object
• You can query either way
– ContentResolver.query() or Activity.managedQuery()
– Second one is better as it causes the activity to manage the life cycle of the Cursor
11/24/2011 Satish Srirama 18/55
Querying a Content Provider -
continued
• Make the queryCursor managedCursor = managedQuery(
android.provider.Contacts.People.CONTENT_URI, //URI
projection, // Which columns to return null, // Which rows to return (all rows)null, // Which rows to return (all rows)null, // Selection arguments (none)People.NAME + " ASC“ // Put the results in ascending order by name
);
SELECT ename from employee WHERE ename='value1' OR ename='value2'
11/24/2011 Satish Srirama 19/55
Reading retrieved data
People.NAME + " ASC");
11/24/2011 Satish Srirama 20/55
Modifying the data
• Modifying Data– Adding records
ContentValues values = new ContentValues();values.put(People.NAME, “Satish Srirama");
…
Uri uri = getContentResolver().insert(People.CONTENT_URI, getContentResolver().insert(People.CONTENT_URI, values);
– Adding new values
– Deleting a record
ContentResolver.delete()
• More info http://developer.android.com/guide/topics/providers/content-providers.html
11/24/2011 Satish Srirama 21/55
Contact picker
• Demo & Exercise
– How to pick contacts from the device using
content provider
– Expose with Intent– Expose with Intent
– Using SimpleCursorAdapter for list
http://thinkandroid.wordpress.com/2010/01/09/si
mplecursoradapters-and-listviews/
11/24/2011 Satish Srirama 22/55
Storage of data with Android
• We can put data into a preferences file.
• We can put data into a ‘normal’ file.
• We can send data across the network to a
serviceservice
• We can use a local database on the handset
– We have seen the content providers
– We can also use SQLite db
11/24/2011 Satish Srirama 23/55
Preference files
• They are a light-weight option
• Call Context.getSharedPreferences() to read and write values as key-value pairs.
• Use Activity.getPreferences() with no • Use Activity.getPreferences() with no name to keep them private to the calling activity
• These are not sharable across applications
– you expose them as a ‘content provider’
• Used to store the state of an application
11/24/2011 Satish Srirama 24/55
Files in Android
• We can write larger data to file
• You can only access files available to the application– res/raw/mydata
• Reading data from a file• Reading data from a file
– Context.openFileInput() – Returns
FileInputStream object
• Writing to a file
– Context.openFileOutput() - Returns a FileOutputStream object
11/24/2011 Satish Srirama 25/55
Persisting data to a db
• Android API uses the built-in SQLite db
• Each db is private to the application
– You can expose the db as a content provider
• Creating a Content Provider -• Creating a Content Provider -
http://developer.android.com/guide/topics/providers/c
ontent-providers.html
• All databases, SQLite and others, are stored on
the device in /data/data/package_name/databases
11/24/2011 Satish Srirama 26/55
Services
• Faceless components that run in the background– Example: music player, network downlaod, etc.
• Can run in your own process or separate process
• They can perform long-running operations in the backgroundbackground– They have higher priority than the background activities
• So safe from the runtime memory management
• A service can essentially take two forms– Started - startService() - run in the background indefinitely,
even if the component that started it is destroyed
– Bound – An application component binds to the service by calling bindService()
11/24/2011 Satish Srirama 27/55
Services - continued
• Explicitly starting new ServiceIntent intent = new Intent(this,
HelloService.class);
startService(intent);
• Services also have their life cycles managed• Services also have their life cycles managed
• You can also start java threads in Services
http://developer.android.com/guide/topics/fun
damentals/services.html
11/24/2011 Satish Srirama 28/55
Homework
• Extend the contact picker to save the state
– Also replace the TextView with ListView
• Extend the todo list to store values in SQLite
DBDB
11/24/2011 Satish Srirama 29/55
Location Based Services
• We have discussed them extensively in
Lecture 2
• Google Maps API is widely used on the web
for LBSfor LBS
• The Android SDK provides support for easily
integrating the Google Maps API
– Applications require a Map API Key in order to use
Google Maps
11/24/2011 Satish Srirama 30/55
Keys
• Apps must be signed in order to deploy them
on a device
• Eclipse automatically creates a signed
debug.keystore that is used when launching debug.keystore that is used when launching
our app from Eclipse
• In order to deploy our app to the public, we
must create a signed keystore
11/24/2011 Satish Srirama
http://developer.android.com/guide/publishing/app-signing.html#ExportWizard
31/55
Google Maps API key
• Find your keystore
• Get your certificate fingerprintkeytool -list -alias satish –keystore
c:\Users\..\.keystore
• Register your certificate with Google
http://code.google.com/android/maps-api-
signup.html
• You see the description of a key and an
example MapView
11/24/2011 Satish Srirama 32/55
Using Google Maps
• Configuration
– Maps require the Google API as the project build target
– AndroidManifest.xml– AndroidManifest.xml<uses-library android:name="com.google.android.maps”/>
<uses-permissionandroid:name="android.permission.INTERNET"/>
• Create a MapView in a MapActivity
11/24/2011 Satish Srirama
http://code.google.com/android/add-ons/google-apis/maps-overview.html
33/55
Working with MapView
• Contains a map
– Map tile retrieval and caching is all done
automatically
• Includes pan• Includes pan
• Includes zoom setBuiltInZoomControls(true);
• You can set modesetSatellite(true);
setTraffic(true);
setStreetView(true);
11/24/2011 Satish Srirama 34/55
MapController
• You can pan and zoom the map
MapView myMap = (MapView)findViewById(R.id.myMap);
MapController mapController = MapController mapController = myMap.getController();
mapController.setZoom(1); //widest zoom/far away
…
mapController.setZoom(21); //narrowest zoom/close in
mapController.zoomIn(); //one level
mapController.zoomOut(); //one level
11/24/2011 Satish Srirama 35/55
GeoPoint
• You can move to a particular point
MapView myMap = (MapView)findViewById(R.id.myMap);
MapController mapController = myMap.getController();myMap.getController();
Double lat = 37.123456 * 1E6;
Double long = -122.123456 * 1E6;
GeoPoint point = new GeoPoint(lat.intValue(), long.intValue());
mapController.setCenter(point); //jump to point
…
mapController.animateTo(point); //smooth transition to point
11/24/2011 Satish Srirama 36/55
Getting access to a location
• LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;LocationManager.GPS_PROVIDER;
Location currentLocation = locationManager.getLastKnownLocation(provi
der);
double lat = location.getLatitude();
double lng = location.getLongitude();
11/24/2011 Satish Srirama 37/55
Reverse Geocoding
• Finding address from longitude/latitude
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double lat = location.getLatitude();double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gc.getFromLocation(lat, lng, 10);
} catch (IOException e) {}
11/24/2011 Satish Srirama 38/55
Forward Geocoding
• Find longitude/latitude (and more) from address
Geocoder gc = new Geocoder(this, Locale.US);
List<Address> addresses = null;
try {try {
addresses = gc.getFromLocationName( “123 Main St., Newton, Kansas”, 10);
} catch (IOException e) {}
double lat = addresses.get(0).getLatitude();
String zip = addresses.get(0).getPostalCode();
11/24/2011 Satish Srirama 39/55
You can set the criteria
• Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String bestProvider = locationManager.getBestProvider (criteria, true);
11/24/2011 Satish Srirama 40/55
Notify changes in location
• LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
updateWithNewLocation(location);
}
…
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
11/24/2011 Satish Srirama 41/55
Exercise
• Demo– Creating a .apk file
– Getting the map key
– Creating a MapView
– Display - where am I–
– Home work• Make my current location to map center
• Work with Map overlay
• Put an overlay where I am
• Put some points of interest
• BONUS - Come with some interesting idea of using the maps (with implementation) – 5 points each for max 5 persons
11/24/2011 Satish Srirama 42/55
MOBILE CLOUD RESEARCH
11/24/2011 Satish Srirama 43
What is Cloud Computing?
• Computing as a utility– Utility services e.g. water, electricity, gas etc
– Consumers pay based on their usage
• Cloud Computing characteristics – Illusion of infinite resources– Illusion of infinite resources
– No up-front cost
– Fine-grained billing (e.g. hourly)
• Gartner: “Cloud computing is a style of computing where massively scalable IT-related capabilities are provided ‘as a service’ across the Internet to multiple external customers”
Satish Srirama11/24/2011 44/55
Mobile Cloud Services
• Efficiently utilizing cloud resources in
increasing the scope of mobile applications
• Some of the process intensive services• Some of the process intensive services
– Processing sensor information
– Face recognition
– Processing videos
11/24/2011 Satish Srirama 45/55
CroudSTag – Scenario
• CroudSTag takes the pictures/videos from the cloud and tries to recognize people
– Pictures/Videos are actually taken by the phone
– Processes the videos
– Recognizes people using facial recognition technologies– Recognizes people using facial recognition technologies
• Reports the user a list of people recognized in the pictures
• The user decides whether to add them or not to the social group
• The people selected by the user receive a message in Facebook inviting them to join the social group
11/24/2011 Satish Srirama 46/55
Screenshots
Used cloud services
Facial Recognition
Process
Taking picture/video
using the camera
Selecting CloudMain Menu
Send Asynchronous
Notification and Results
Storage Services
1.
2.
3.
Login
11/24/2011 Satish Srirama
Send invitation to the
social group
Selecting people
Selecting Cloud
Authentication
Start Process
4.
5.
6.
7.
8.
9.
Send next
invitation
Back to Menu
47/55
Technological Choices - Problems
• Cloud Interoperability– Data and application integration
– Several and different API for each service and vendor
• Invocation of resource intensive tasks from phonesphones– Time and resource consuming task
• Mobile platform integration with cloud services– Android
– iOS
– Windows Phone 7
11/24/2011 Satish Srirama 48/55
Mobile Cloud Middleware (MCM)
11/24/2011 Satish Srirama 49/55
MCM – enables
• Interoperability between different Cloud
Services (IaaS, SaaS, PaaS) and Providers
(Amazon, Eucalyptus, etc)
• Bringing the benefits of the Cloud to the • Bringing the benefits of the Cloud to the
Mobile Domain
• Composition of different Cloud Services
• Asynchronous communication between the
device and MCM
11/24/2011 Satish Srirama 50/55
Technological Choices – Asynchronous
Notification
• Via third party services
– Apple Push Notification Service (APNS)
– Android Cloud to Device Messaging Framework (C2DM)
– Microsoft Push Notification Service (MPN)– Microsoft Push Notification Service (MPN)
• Mobile Host [Srirama et al, 2006]
– Providing web services from smart phones
– MCM can directly send the response back to the device
– Support for Android, iOS and J2ME
11/24/2011 Satish Srirama 51/55
How you can contribute?
• Several open Bachelor/Master theses
http://ds.cs.ut.ee/theses
• Your course projects can be extended to
thesestheses
• All new interesting ideas are welcome
• Good students always have paid positions
– Contact srirama AT ut.ee
11/24/2011 Satish Srirama 52/55
Reminder
• Finish the homework and all the exercises
discussed in the lecture
• Send by mail to me
– Put cc to [email protected]– Put cc to [email protected]
• Deadline for homework 29th November 2011
11/24/2011 Satish Srirama 53/55
Preliminary presentation of projects
• Next week , Thursday 1st December 2011
• Each group gives a talk of 15 - 20 min– Explain the problem in your words
– Make use of slides
– How you are addressing them– How you are addressing them
– How far you have reached
– Do you see any problems
– What is the contribution from individuals
• If you have preliminary demonstration then it is very good – Take additional 5 min
11/24/2011 Satish Srirama 54/55
References
• Android developers
http://developer.android.com/
• Books
– “Professional Android 2 Application – “Professional Android 2 Application
Development”, By Reto Meier
11/24/2011 Satish Srirama 55/55