• Separated from application code
• Maintain independently
• Externalizing resources allows to provide alternative resources that support specific device configurations
• Default and alternative resources
• Qualifiers in directory names
• Located in subdirectories of res/ directory [fragile]
3.20. Resource types
• Animation
• Saved in res/anim/ or res/drawable/
• Accessed from the R.anim or R.drawable class
• Color State List
• res/color/ - R.color
• Drawable
• Res/drawable/ - R.drawable
• Layout
• res/layout/ - R.layout
• Menu
• res/menu/ - R.menu
• String
• res/values/ - R.string, R.array, R.plurals
• Style
• res/values/ - R.style
• Other resource types
• res/values/ - R.* (e.g. R.bool, R.integer, R.dimen, etc.) [fragile]
3.21. Qualifiers
• Appear in resource directory names:
• To support specific device configuration
• e.g. different layout for landscape and portrait view
• layout-port contains layout for portrait orientation and layout-land contains layout for landscape
• Multiple qualifiers: drawable-port-hdpi/
• The qualifiers must be in a specific order (check out: developer.android.com)
• Examples
• Language for localization: en, fr, hu, etc.
• Screen size: small, normal, large, xlarge
• Pixel density (dpi): ldpi, mdpi, hdpi, xhdpi, nodpi, tvdpi
• Platform version (API level): v3, v4, v7, etc.
• etc.
3.22. Example 1/2
• Layout
3.23. Example 2/2
• String
• Menu
3.24. ADVANCED USER INTERFACE
[fragile]
3.25. Android Fragment Framework
• Fragment: represents a behavior or a portion of user interface in an Activity
• Advantages
• Modularize the code
• Reuseable: use in multiple activities
• Adjust the user interface to the screen
• Multiple layouts based on the size of the display
3.26. Fragment and Activity
• Fragments are attached to an Activity
• Their lifecycles almost the same
3.27. Fragment lifecycle
3.28. Different display sizes
[fragile]
3.29. UI Fragment
• Create
• Extend Fragment class and override onCreateView() method
3.30. UI Fragment
• Attach
• Dynamic
• Load the proper Fragment in runtime
• Static
• In Layout XML
[fragile]
3.31. Managing Fragments
• Manage fragments withFragmentManager class
• Activity: .getFragmentManager()
• Starting FragmentTransaction
• Find fragments with id or tag
• Managing Fragment-stack [fragile]
3.32. FragmentTransaction
• Modify active fragments throughFragmentTransaction
• Starting with the beginTransaction() method in FragmentManager
• Important methods
• add(), remove(), replace(): add or remove fragments in an Activity
• commit(): execute transaction
• show(), hide(): show or hide fragment instance
• setTransition(), setCustomAnimations()
• addToBackStack(): transaction can be added to back stack [fragile]
3.33. Communication
• Fragments have to be encapsulated indirect communication
• Activity acts like a mediator
If direct communication is needed:
setTargetFragment() getTargetFragment() [fragile]
3.34. FragmentDialog
• Fragment can appear as a dialog
• Dialog with custom layout
• Dialog has the same lifecycle as Fragment
• Fragment Dialog can be added to back stack
• DialogFragment is also a Fragment
• It can be shown as a part of an Activity layout [fragile]
3.35. Fragment parameters
• Fragment can be instantiated with its default constructor
• If additional parameters are needed
• Pass them with Bundle
• setArguments()
• The Bundle stores the data during initiation
• getArguments()
• The Bundle survive the changing of orientation [fragile]
3.36. Fragments in older versions
• Official support library
• Static class library
• Support from Android 1.6
• Support for additional components which come with new Android versions
• Loader framework
• GridLayout
[fragile]
3.38. FragmentPagerAdapter
• Usually the pages of ViewPager are Fragments
• FragmentPagerAdapter provides the pages
• Working is similar to BaseAdapter
• Fragment getItem(int position): returns the proper fragment
• int getCount(): returns the number of pages
• String getTitle(int position): returns the title of the given page [fragile]
3.39. PageTitleStrip and PageTabStrip
• Widgets which show the titles of pages in ViewPager
PageTitleStrip non-interactive
PageTabStrip interactive
3.40. ANIMATIONS
3.41. Property Animation
• Allow to animate almost anything
• Components
• Animators: provide the basic structure for creating animations
• Evaluators: tell the property animation system how to calculate values
• Interpolators: tell how specific values in an animation are calculated as a function of time
3.42. Property Animation elements
• Duration: the duration of an animation
• Time interpolation
• Repeat count and behavior
• Animator sets: group animations to play together or sequentially or after specified delays
• Frame refresh delay: how often to refresh frames of the animation
3.43. View animation
• Preform tween animation on View objects
• Base animations
• Rotate, scale, translate, alpha
• Defined by XML or Java code, but XML is preferred
3.44. Drawable animation
• Load a series of Drawable resources one after another
• Traditional animation which plays images like a roll of a film
3.45. Summary
• Communication between components with Intents
• Resources are separated from application code
• Qualifiers to create alternative resources
• Advanced UI with reusable Fragments
• Support library for older Android versions
• Create multiple layouts for different display sizes
• Three type of animations to create complex UI animations
• Drawable, View and Property animation
4. 4 Persisting and binding data on Android platform, Broadcast Receiver Component
4.1. Lecture 4 - Outline
• Persistent Data Storage
• Content Provider
• Data Binding
• Broadcast Receiver
4.2. PERSISTENT DATA STORAGE
4.3. Persistent Data Storage
• There are 4 ways
• Shared Preferences
• Store private primitive data in key-value pairs
• Files
• Store data on device memory or on external storage
• SQLite Database
• Store structured data in private database
• Network
• Store data on the web [fragile]
4.4. Shared Preferences
• Store private primitive data in key-value pairs
• boolean, float, int, long, String, Set<String>
• Data will be persisted across user sessions
• Even if the application is killed
• SharedPreferences class is an interface for accessing and modifying preference data
• Modifications through SharedPreferences.Editor object [fragile]
4.5. Using Shared Preferences - Write
• Call edit() to get a SharedPreferences.Editor
• Add values with put...() methods
• Commit new values with commit() method
[fragile]
4.6. Using Shared Preferences - Read
• Call the proper get...() method in SharedPreferences
[fragile]
4.7. Internal and External Storage
• Read and write files
• Internal/phone storage
• External storage / SD card
• Operations with standard Java objects
• FileOutputStream, FileInputStream
• Files can be private or public
• public: readable and/or writeable by others
• Read and write files
• Internal/phone storage [fragile]
4.8. Internal Storage example
• Create and write a file to internal storage
• Read file with openFileInput() and read() method of FileInputStream [fragile]
4.9. External Storage example
• Create and write a file to internal storage
• Read file with openFileInput() and read() method of FileInputStream [fragile]
4.10. SQLite Database
• Full support for SQLite databases
• Private database, not accessible from outside the application
• Manage with SQLiteOpenHelper and SQLiteDatabase objects
• SQLite queries return Cursor objects
• Navigate and read
4.11. SQLite Example 1/3
4.12. SQLite Example 2/3
4.13. SQLite Example 3/3
• Get one row
• Insert new row
[fragile]
4.14. Network Connection
• Use network to store data on a web-based service
• Standard Java package or Android specific package
• java.net.*
• android.net.*
4.15. CONTENT PROVIDER 4.16. Content Provider
• Manage access to a structured set of data
• Standard interface to share data with other applications
• Android hasn't got any storage which any application can access
• Built-in content providers
• Contacts, calendar events, files
• Accessible to any Android application
• Need to register Content Provider
• Every resource has unique URI
4.17. Similar Conceptions
• Web page
• Domain registration is required
• REST: REpresentational State Transfer
• Unique URI for data
• WebService
• Provides operations through services
• Stored procedures
• Service based access to database
4.18. Example 1/3
[fragile]
4.19. Query data
• With query() method of ContentResolver
• startManagingCursor(): to manage the lifecycle of the Cursor
• Parameters:
• URI
• Column names
• WHERE conditions
• Order conditions [fragile]
4.20. Query data
• Returns: Cursor with 0+ row
• Data is only readable with Cursor
• moveToFirst()
• moveToNext()
• moveToPrevious()
• getCount()
• getColumnIndexOrThrow()
• getColumnName()
• getColumnNames()
• moveToPosition()
• getPosition()
4.21. Example 2/3
[fragile]
4.22. Insert and Modify
• With ContentValues key-value pairs
• Insert new key-value with put() method
• ContentResolver.insert(...)
• Returns with the URI of the new element
4.23. Example 3/3
[fragile]
4.24. Create Custom Provider 1/2
• Extend ContentProvider class
• Open data in onCreate() method
• Thread-safe implementation!
• Define column names with public staticString variables
• Define _id column to identify rows
• In SQLite: INTEGER PRIMARY KEY AUTOINCREMENTATION [fragile]
4.25. Create Custom Provider 2/1
• Override methods:
• query(), insert(), update(), delete(), getType()
• Register Content Provider in
4.26. DATA BINDING
[fragile]
4.27. Data Binding
• Simple way to present and interact with data
• AdapterView is a view whose children are determined by an Adapter
• ListView, Gallery, Spinner, GridView, etc.
• Adapter supplies the data
• Adapter is responsible for drawing the View for each data element
• Concrete implementations: ArrayAdapter, CursorAdapter
4.28. Example - ArrayAdapter
4.29. Another example 1/2
4.30. Another example 2/2
4.31. Example - Google autocomplete
4.32. BROADCAST RECEIVER
[fragile]
4.33. Broadcast Receiver
• Allow to register for system or application events
• Types:
• Normal: all receivers will be called in random order
• Ordered: running one at the time
• Components can be ordered by priorities and can terminate calls for lower priorities
• Catch messages with BroadcastReceiver component
• Extend BroadcastReceiver class
• Override onReceive() method
• Create an intent filter
• 5 seconds time limit!
• There are built-in Broadcast Intents (generated by the system), e.g.:
•
• sendBroadcast() method allows to send custom Broadcast Intents
• It is intent so it can contain extra data
4.36. Example - Monitoring calls
• Monitoring incoming and outgoing calls
• Incoming and outgoing calls generate Broadcast messages
• Support a few kind of event about phone calls
•
•
•
• Additional data can be determined (e.g. caller id)
• Required permissions
•
•
4.37. Example - Registration of receivers
4.38. Example - handle incoming calls
4.39. Example - handle outgoing calls
4.40. Example - screenshot
4.41. Summary
• Store data in persistent data storage
• SharedPreferences, Files, Database, Network
• Use Content Provider to share data with other applications
• Built-in providers for contacts, events, files
• Manage model-view connection with data binding
• BroadcastReceiver to notify components about events
• Built-in broadcast messages
5. 5 Network communication, Location based services, Service component
5.1. Lecture 5 - Outline
• Network communication
• Location based services
• ProximityAlert, Geocoding, MapActivty and MapView
• Services
5.2. NETWORK COMMUNICATION
[fragile]
5.3. Mobile network information
• TelephonyManager object
• TelephonyManager tm = (TelephonyManager)getSystemService(Context.
);
• Accessible information
• Call state, cell locations, operator name, imei, etc.
• Monitoring mobile network state with PhoneStateListener
• tm.listen(listener, event);
5.4. Examples
• Cell information
• Operator and SIM data
• Monitoring signal strength
5.5. HTTP communication
• HTTP queries with HTTP GET and POST parameters
• Full HTTPS support
• HTTP library created by Apache
• Need permission
•
• Basic rules:
• Work in new thread!
• Check response code!
5.6. HttpClient and DefaultHttpClient
• HttpClient
• HTTP client interface
• Executes HTTP requests
• Cookie management
• Authentication support
• DefaultHttpClient
• Concrete implementation of HttpClient interface
• AndroidHttpClient
• Extends DefaultHttpClient with Android specific settings [fragile]
5.7. HttpGet
• Standard HTTP GET implementation
• org.apache.http.client.methods.HttpGet
• Automatically follows redirects
• To disable: setFollowRedirects(false);
• Instantiate
• HttpGet httpGet = newHttpGet(,,http://www.google.com'');
• Execute with execute(...) method of HttpClient [fragile]
5.8. Result of HTTP request
• execute() method returns HttpResponse object
• Get reply status
• StatusLine object which contains status code
• HttpStatus: store HTTP statuses as constants
• Get content of response
• HttpEntity object
• HttpEntity entity =response.getEntity();
[fragile]
5.9. HttpEntity
• Both request and response can contain HttpEntity
• 3 main types:
• Streamed: get content as a stream
• Self-contained: content is stored in memory
• Wrapping: content is wrapped in another entity
• Get content
• InputStream is =entity.getContent();
5.10. HTTP GET example
5.11. Modifying UI from another thread
• The system creates a main thread at application start (UI thread)
• Long-running operations can block UI
• Run in new thread!
• Results of these operations usually indicate UI update which is only allowed from UI thread
• Solutions:
• Activity.runOnUiThread(Runnable)
• View.post(Runnable)
• View.postDelayed(Runnable, long)
• Handler
• AsyncTask
[fragile]
5.12. URL encoding
• GET parameters cannot contain special characters
• Only alphanumerics [0-9a-zA-Z] and some characters ( ) are allowed
• URLs should be encoded everywhere in a request
• URL encoding converts special characters into a format that can be transmitted
• URLEncoder
• encode(String s)
• encode(String s, String charsetName)
• URLDecoder
• decode(String s)
• decode(String s, String encoding) [fragile]
5.13. HTTP POST
• Standard Http Post message
• org.apache.http.client.methods.HttpPost
• Parameters do not appear in URL
• Typical usage:
• Uploading files
• Sending data to database
• etc.
5.14. HTTP POST example
5.15. HTTPS
• Secure HTTP requests
• All data are encrypted
• Typical usage
• Generate certificate
• Set HTTPS server with the generated cert.
• Use certificate in the Android application
• Use HttpsUrlConnection class on Android
5.16. Processing responses
• Usually predefined protocol for client-server communication
• Most of the times a third party server replies data in common protocol
• Typical formats
• CSV (Comma Separated Value(s))
• JSON (JavaScript Object Notation)
• XML (Extensible Markup Language)
• Built-in parsers on Android
5.17. JSON
• Structural characters: '{', ']' ,'[', ']' ,':' ,';'
• Example:
[fragile]
5.18. Processing JSON
• JSONObject
• Parsing JSON objects
• Get elements with key
• getString(String name)
• getJSONObject(String name)
• getJSONArray(String name)
• Create JSON objects from String or Map
• JSONArray
• For JSON arrays
• Parse and query by index
• Create from Collection
5.19. JSON example
5.20. XML
[fragile]
5.21. Processing XML
• Rich possibilities for parsing XML data on Android
• SAX parser
• javax.xml.parsers.SAXParser
• event based parser
• generate events when parser reaches specific parts of the data
• call back with specific functions
• DOM parser
• javax.xml.parsers.DocumentBuilder
• javax.xml.parsers.DocumentBuilderFactory
• parsed XML is stored in memory as a tree
5.22. XML example
[fragile]
5.23. TCP/IP socket
• Standard socket implementation
• With well-known java.net.Socket class
• java.net.ServerSocket class for incoming connections
• local applications can communicate with each other through localhost
• Read and write with InputStream and OutputStream
5.24. LOCATION BASED SERVICES
5.25. Location based services
• Mobile phones are portable
• Application can use location to provide extra information
• Navigation
• Meeting organization based on routines
• Enterprise applications: fleet tracking
5.26. Current Position
• Location Manager
• Obtain current location
• Track movement
• Set proximity alerts for detecting movement into and out of a specified area
• Location Provider
• Based on mobile cells
• Fine location: GPS
• Permissions
•
•
5.27. Providers
• Example
• Different capabilities
• power consumption, monetary cost, accuracy
• ability to determine altitude, speed or heading
• Criteria object for get the best provider
• accuracy criteria, power requirement criteria, altitude required, etc.
5.28. Examples
• Get current location (last known location)
• Request location update (based on time or distance)
5.29. ProximityAlert
• Android can notify when mobile move into or out a specified area
• Coordinate and radius
• Intelligent logic for using the correct provider
5.30. Geocoding
• GPS coordinate from address
• Synch call!
5.31. Reverse Geocoding
• Address/addresses from GPS coordinate
5.32. MapView
• Displays coordinates on Google map
• Full control of view
• location, zoom level, type (map, satellite, traffic)
• Can contain overlays
• Can contain custom POIs
5.33. MapView screenshot
[fragile]
5.34. Creating MapView
• Only in activity which extends MapActivity
• MapView in layout XML
• Internet permission is required
• Override isRouteDisplayed() method
• Personalized API key is required
• Using MapView
• Set layers with setSatellite(), setStreetView(), setTraffic() methods
• Get center, current zoom, max zoom, etc.
• Control map with MapController object
• set center, zoom level, etc.
5.35. MapView - Layout
[fragile]
5.36. MapView Overlays
• MapView can contain any number of Overlay
• You can draw anything on overlay
• You can be notified about touch events
• Automatic mapping from pixels to GeoPoint with Projection class
• ItemizedOverlay class to display POIs automatically
• Store POIs as OverlayItem objects
5.37. Creating Overlay
5.38. SERVICES 5.39. Service
• Application component
• Perform a longer-running operation while not interact with the user
• Service has no UI
• Service has its own lifecycle
• Other applications can interact with the service
• Take care of closing resources and stopping the service!
• Examples: music player, downloader application (e.g. torrent), etc.
[fragile]
5.40. Service types
• Started
• Service started with startService() method by a component
• Usually perform a single operation
• When the operation is done, the service should stop itself
• Bound
• An application component binds to the service by calling bindService()
• Offers a client-server interface to interact with the service in both ways
• Run only as long as another application component is bound to it
• Custom service can support both types at the same time
5.41. Service lifecycle
5.42. Managing Services
• The usage is similar to activities
• Communicate through Intents
• Service runs in the main thread of its process by default
• Long-running or blocking tasks should be executed in new thread
• e.g. CPU intensive work, MP3 playback, networking
• if not: well-known Application Not Responding (ANR) [fragile]
5.43. Creating Service
• Extend Service class
• Override required methods
• Take care of proper termination
• Close resources
• Stop service
• Register the Service in as an application component
• Start the Service
• startService() or bindService() [fragile]
5.44. Custom Service methods
• onStartCommand()
• automatically called when another component starts the service
• onBind()
• automatically called when another component binds to the service
• onCreate()
• called when the service is created
• before onStartCommand() and onBind()
• onDestroy()
• called before the service has been destroyed
5.45. Terminating services by Android OS
• Android OS stops services only if the Activity in the foreground needs more memory
• Lower the chance that the service will be destroyed
• If a service is bound to an Activity
• Foreground Services are almost never killed by the system
• If there is enough free memory again then the system trying to restart the service
5.46. Service attributes 1/2
5.47. Service attributes 2/2
• enabled: determine that the service can be instantiated by the system
• exported: whether or not components of other applications can invoke the service or interact with it
• icon: icon of the service
• label: a name for the service that can be displayed to users
• name: package name where the implementation is
• permission: which permissions are required to connect to this service
• process: the name of the process where the service is to run
5.48. Service example
• Custom Service
• Starting the Service
5.49. Summary
• Network communication
• Standard interfaces for standard protocols
• Location based services
• Lot of possibilities to monitoring location
• Geocoding and reverse geocoding to transform coordinates to addresses and back
• Custom Google Map based views with MapView
• Use Service to perform long-running operations in the background
• Independent from UI
6. 6 Introducing the iOS Mobile Platform, Developer
Tools and Programming basics
6.1. Lecture 6 - Outline
• Platform summary
• Developer Tools and Programming basics
• Architecture of the iOS applications
6.2. Devices running iOS
• iPhone
• iPhone, iPhone 3G, iPhone 3GS, iPhone 4, iPhone 4GS, iPhone 5
• iPod Touch
• iPod Touch 1st, 2nd, 3rd, 4th, 5th generation
• iPad
• iPad 1, iPad 2, iPad 3, iPad 4, iPad Mini
• (Apple TV)
6.3. iOS the Operating System
• Derived from core OS X technologies
• Nearly the same kernel (XNU)
• UNIX/BSD fundaments
• iOS application are not compatible with OS X
• Closed platform with numerous restrictions
• Development only with the official iOS SDK only in OS X environment
6.4. Behind success
• Innovative User Interface
• Touchscreen
• Multitouch support
• Fast and fluent
• A real Mobile web browser: Safari
• App Store: centralized application store
• "There is an App For That!"
• The developers get popularity only for a small percent of the profit
• Common Components
• Human Interface Guidelines
• Apple fanboy effect
6.5. Drawbacks
• API weakness, no full multitasking
• Became even better
• Requires OS X for development
• Requires iTunes for data synchronization
• Unable to use as USB pendrive
• Applications are available only through App Store
• Apple decides which applications can be published through the Store. Many critics.
• Customization requires Jailbreak
• No integrated FM radio (only external)
• Expensive
6.6. Drawbacks
• API weakness, no full multitasking
• Became even better
• Requires OS X for development
• Requires iTunes for data synchronization
• Unable to use as USB pendrive
• Applications are available only through App Store
• Apple decides which applications can be published through the Store. Many critics.
• Customization requires Jailbreak
• No integrated FM radio (only external)
• Expensive
6.7. The History of the iPhone
• API weakness, no full multitasking
• 2007. june: itroduces iPhone 1.0
• 2008. march: introduces the iPhone SDK
• The begining of 3rd party application development
• 2008. july: introduces iPhone 3G and iOS 2.0 and opens the App Store
• 2010. april: introduces iPad (from than on the operation system is officially called iOS)
• Currently iPad 4, iPhone 5
6.8. iOS versions from user perspective
• iOS 1: fix 20 applications (Mail, Messages, Maps, ...)
• iOS 2: App Store, A-GPS
• iOS 3: MMS, copy-paste, Spotlight search, Push Notification, IMAP, compass
• iOS 4: multitasking, app folders, inbox, Game Center, iAd
• iOS 5: Notification Center, iCloud, iMessage, native Twitter, Siri
6.9. iOS versions from developer perspective
• iOS 1.0: only web based 3rd party applications
• iOS 2.0: native 3rd party applications, iOS SDK, App Store
• iOS 3.0-3.2: MMS, copy-paste, Spotlight search, Push Notification, IMAP, compass
• iOS 4.0-4.3: New application life-cycle model, background tasks, easier thread handling(blocks), Xcode 4
• iOS 5.0: automatic reference counting (ARC), storyboards
6.10. Hardware, common properties
• ARM architecture based processors(ARMv6 és ARMv7 instruction set)
• Display resolutions:
• iPhone5: 640 x 1136, 960x640 (iPhone 4-4S, "Retina display"), 480x320
• iPad: 2048x1536 (iPad 3+), 1024x768 (iPad 1-2, iPad Mini)
• Simultaneous multitouch points:
• iPhone: 5
• iPad: 11
6.11. iPhone 5 interiors
• Display: 640 x 1136 IPS TFT, capacitive touch screen
• SoC: Apple A6 (Dual-core 1.2 GHz ARM Coretex-A9)
• RAM: 1 GB
• Wireless radio:
• 3G, HSDPA, HSUPA
• Wi-Fi 802.11 b/g/n,
• Bluetooth 4.0
• A-GPS, GLONASS, accelerometer, gyroscope, compass
• Capacity: 16/32/64 GB
• Camera: 8 MP, autofocus
• Accumulator: 1440 mAh
6.12. UDID: Unique Device Identifier
• Every iOS device have a globally unique identifier, which is a 40 character hexa string
• This identifies the test device during the application development
• It can be get with Xcode Organizer or with iTunes: Summary view, than one clikk on "Serial Number"
filed
• Hint: Cmd + C will copy to clipboard
• Hint: Cmd + C will copy to clipboard