Android Development 2 Prabhaker Mateti CEG 436 Mobile
Android Development - 2 Prabhaker Mateti CEG 436: Mobile Computing (PM)
Agenda • • Android. os classes, debug java. io refresher Activities and Tasks Processes and Threads Android Location Service Google Maps External Library Code Example: Simple. Networking Code Example: Android Location Service CEG 436: Mobile Computing (PM) 2
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. Death. Recipient • Iinterface Base class for Binder interfaces. • Parcelable cf. serializable, marshalled result • Recovery. System. Progress. Listener CEG 436: Mobile Computing (PM) 3
android. os classes • Async. Task<Params, Progress, Result> enables proper use of the UI thread. • Battery. Manager • Binder remotable object; RPC mechanism defined by IBinder. • Bundle A mapping from values to Parcelable types. • Condition. Variable a locking paradigm. • Environment • Memory. File wrapper for the Linux ashmem (Anonymous SHared MEMory) driver. CEG 436: Mobile Computing (PM) 4
android. os classes • Parcel Container for a message (data and object references) that can be sent through an IBinder. • Pattern. Matcher A simple pattern matcher; not full reg-exp, only simple globbing. • Recovery. System the separate partition that can be used to install system updates, wipe user data, etc. • Strict. Mode while developing … CEG 436: Mobile Computing (PM) 5
android. os. Debug • debugging functions for Android applications, including tracing and allocation counts. • start. Method. Tracing(String trace. Name, int buffer. Size, int flags) • dump. Service (String name, File. Descriptor fd, String[] args) • get. Memory. Info (Debug. Memory. Info memory. Info) • thread. Cpu. Time. Nanos () CEG 436: Mobile Computing (PM) 6
java. io. File. Output. Stream • public File. Output. Stream (File file, boolean append) • public void write (byte[] buffer, int offset, int byte. Count) • public void close () • Buffered. Output. Stream CEG 436: Mobile Computing (PM) 7
java. io. File. Input. Stream • File. Input. Stream(String path) Equivalent to new File. Input. Stream(new File(path)). • public int read (byte[] buffer, int offset, int byte. Count) • public void close () • Buffered. Input. Stream. CEG 436: Mobile Computing (PM) 8
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. CEG 436 9
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 lifecycle CEG 436: Mobile Computing (PM) 10
Live Wallpapers • similar to a regular Android service. • consumes CPU time, memory, battery • on. Create. Engine() whose goal is to create a Wallpaper. Service. Engine. • source code example: android-sdk-linux_x 86/ docs/resources/samples/Cube. Live. Wallpaper CEG 436: Mobile Computing (PM) 11
Activity • 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 CEG 436: Mobile Computing (PM) 12
Activities • One activity can start another, including one defined in a different application. • Context. start. Activity(Intent) • Activity. start. Activity. For. Result (Intent, Request_Code) • Asynchronous Message (Intent) CEG 436: Mobile Computing (PM) 13
public abstract class Context • extends java. lang. Object – Interface to global information about an application environment. – implementation is provided by the Android system. • Selected methods 1. 2. 3. 4. 5. 6. 7. File get. External. Files. Dir(String type) File. Output. Stream open. File. Output(String name, int mode) Intent register. Receiver (Broadcast. Receiver, Intent. Filter, String broadcast. Permission, Handler scheduler) void send. Broadcast(Intent intent, String receiver. Permission) void start. Activities(Intent[] intents) Object get. System. Service(String name) Component. Name start. Service(Intent service) CEG 436: Mobile Computing (PM) 14
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 them • Optionally associated with a window (UI) • Have an execution Context CEG 436: Mobile Computing (PM) • More of a notion than a concrete API entity • A collection of related Activities • Capable of spanning multiple processes • Associated with their own UI history stack • What users on other platforms know as “applications” 15
android. os. Process public static final int FIRST_APPLICATION_UID public Process () public static final void kill. Process (int pid) public static final void send. Signal (int pid, int signal) • public static final int get. Thread. Priority (int tid) • public static final void set. Thread. Priority (int priority) • • CEG 436: Mobile Computing (PM) 16
Processes • 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 resources. CEG 436: Mobile Computing (PM) 17
Processes • 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>. CEG 436: Mobile Computing (PM) 18
Main Thread • All components are instantiated in the main thread (aka UI thread) of the specified process. • 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) CEG 436: Mobile Computing (PM) 19
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. Handler. Thread for starting a new thread that has a looper. CEG 436: Mobile Computing (PM) 20
Thread Issues • If the UI thread is blocked for more than a few seconds – "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 CEG 436: Mobile Computing (PM) 21
Async. Task • 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 yourself. • task. A extends Async. Task • implement the do. In. Background() – runs in a pool of background threads. – implement on. Post. Execute(), which delivers the result from the above and runs in the UI thread • run the task. A by calling execute() from the UI thread. CEG 436: Mobile Computing (PM) 22
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 CEG 436: Mobile Computing (PM) 23
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 low. • 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. CEG 436: Mobile Computing (PM) 24
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 start. Foreground(). a Service that's executing one of on. Create(), on. Start(), or on. Destroy(). a Broadcast. Receiver that's executing its on. Receive() 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 responsive. CEG 436: Mobile Computing (PM) 25
Visible process • A process that does not have any foreground components, but still can affect what the user sees on screen. • A process is considered visible if it hosts: – an Activity that is not in the foreground, but is still visible to the user (its on. Pause() 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. CEG 436: Mobile Computing (PM) 26
Service process • A process that is running a service that has been started with the start. Service() 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. CEG 436: Mobile Computing (PM) 27
Background process • A process holding an activity that's not currently visible to the user (the activity's on. Stop() 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. CEG 436: Mobile Computing (PM) 28
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. CEG 436: Mobile Computing (PM) 29
Activities and Tasks • A task is a collection of related Activities. • It is capable of spanning multiple processes. Application 1 (. apk) Application 2 (. apk) Process Activity Activity Content Provider Service CEG 436: Mobile Computing (PM) Service Content Provider Service 30
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 running 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 launcher) • 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. CEG 436: Mobile Computing (PM) 31
Affinities • An affinity means a preference for each activity to belong to a certain task. • An individual affinity can be set for each activity: • By default, a new activity is launched into the task of the activity that called start. Activity(). CEG 436: Mobile Computing (PM) 32
Affinities • If the Intent object passed to start. Activity() 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. • allow. Task. Reparenting == 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. CEG 436: Mobile Computing (PM) 33
Launch Modes • • standard (default) single. Top single. Task single. Instance • A launch mode can be set for each activity • The modes differ from each other on four points … CEG 436: Mobile Computing (PM) 34
Launch Mode Differences-1 • Which task will hold the activity that responds to the intent Original Task New Activity A Root Activity standard/single. Top without FLAG_ACTIVITY_NEW_TASK CEG 436: Mobile Computing (PM) New Activity single. Task/single. Instance 35
Launch Mode Differences-2 • Whethere can be multiple instances of the activity • A "standard" or "single. Top" activity can be instantiated many times. • A "single. Task" or "single. Instance" 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 C Activity B and Activity C are standard/single. Top CEG 436: Mobile Computing (PM) Activity C is single. Task or single. Instance 36
Launch Mode Differences-3 • Whether the instance can have other activities in its task "standard" "single. Top" "single. Task" "single. Instance" CEG 436: Mobile Computing (PM) • These modes permit multiple activities to belong to the task. • A "single. Task" activity will always be the root activity of the task. • An activity stands alone as the only activity in its task. 37
Launch Mode Differences-4 a • Whether a new instance of the class will be launched to handle a new intent Activity D Activity C Activity B Activity A Original Task If D is"standard" If D is"single. Top" Activity C An intent arrives for an activity of type D CEG 436: Mobile Computing (PM) The existing instance D is expected to handle the new intent (since it's at the top of the stack) 38
Launch Mode Differences-4 b • 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 stack) Original Task CEG 436: Mobile Computing (PM) Activity B Activity D Activity C Activity B Activity A If B is"standard" If B is"single. Top" 39
Launch Mode Differences-4 c • Whether a new instance of the class will be launched to handle a new intent (Cont) Activity B Original Task CEG 436: Mobile Computing (PM) An intent arrives for an activity of type B Activity B If B is"single. Instance" A "single. Instance" activity is always at the top of the stack, so it is always in position to handle the intent. 40
Launch Mode Differences-4 d • 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"single. Task" Activity A Activity B Original Task CEG 436: Mobile Computing (PM) An intent arrives for an activity of type 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"single. Task" 41
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 always. Retain. Task. State is set to the root activity – The task retains all activities in its stack even after a long period. • If clear. Task. On. Launch 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. CEG 436: Mobile Computing (PM) 42
Clearing the Stack • If finish. On. Task. Launch 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. CEG 436: Mobile Computing (PM) 43
Activity Lifecycle • Running state: An activity is in the foreground of the screen (at the top of the activity stack for the current task). • 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. CEG 436: Mobile Computing (PM) 44
Activity Lifecycle • on. Create() – – • on. Start() – • – when the system is about to start resuming another activity 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. Stop() – – • 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. on. Pause() – • after the activity has been stopped, just prior to it being started again on. Resume() – – • just before the activity becomes visible to user on. Restart() – • 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. on. Destroy() – Called before the activity is destroyed CEG 436: Mobile Computing (PM) 45
Activity Lifecycle • Three nested loops for the entire lifecycle • Visible Lifetime – During this time, the user can see the activity on screen – on. Start() and on. Stop() 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. CEG 436: Mobile Computing (PM) 46
Saving activity state CEG 436: Mobile Computing (PM) 47
Service Lifecycle CEG 436: Mobile Computing (PM) 48
Service Lifecycle • The service is started by calling – Context. start. Service() • Runs until someone, including itself, calls – Context. stop. Service() • Clients establish a connection to the Service object and use that connection to call into the service. – established by Context. bind. Service() – closed by Context. unbind. Service() CEG 436: Mobile Computing (PM) 49
Broadcast Receiver Lifecycle • Only single callback method • on. Receive(current. Context, Intent broadcast. Msg) • 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. CEG 436: Mobile Computing (PM) 50
Android Location Service CEG 436: Mobile Computing (PM)
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. CEG 436: Mobile Computing (PM) 52
android. location • Address A class representing an Address, i. e, a set of Strings describing a location. • Geocoder A class for handling geocoding and reverse geocoding. • Gps. Status. Nmea. Listener Used for receiving NMEA sentences from the GPS. • Location. Manager This class provides access to the system location services. • For more information, read the guide to Obtaining User Location. CEG 436: Mobile Computing (PM) 53
android. location. Location. Manager • Location. Manager lcm = (Location. Manager) get. System. Service(Context. LOCATION_SERVICE); • listener = new Location. Listener() { … } • lcm. request. Location. Updates(Location. Manager. NETWORK_PROVIDER, a, b, listener); – – NETWORK_PROVIDER == cell phone tower and Wi-Fi GPS_PROVIDER a == minimum time interval between notifications; 0 is ok b == minimum change in distance between notifications; 0 is ok • public void on. Location. Changed(Location ltn) { make. Use. Of. New. Location(ltn); // your method } • public void on. Status. Changed(String provider, int status, Bundle extras) {…} • public void on. Provider. Enabled(String provider) {…} • public void on. Provider. Disabled(String provider) {…} CEG 436: Mobile Computing (PM) 54
Location Use Model for Performance CEG 436: Mobile Computing (PM) 55
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 accuracy. • location. Manager. remove. Updates(listener); • location. Manager. get. Last. Known. Location(pro); • The most recent fix is not always the best. – Choose location fixes based on several criteria. CEG 436: Mobile Computing (PM) 56
Tagging content with location CEG 436: Mobile Computing (PM) 57
Help decide where to go CEG 436: Mobile Computing (PM) 58
Providing Mock Location Data • Eclipse – Window > Show View > Other > Emulator Control • DDMS – 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. CEG 436: Mobile Computing (PM) 59
geocoding • Geocoder gcd = new Geocoder( context, Locale. get. Default()); List<Address> addresses = gcd. get. From. Location(latit, longi, 1); if (addresses. size() > 0) System. out. println( addresses. get(0). get. Locality()); CEG 436: Mobile Computing (PM) 60
GPS CEG 436: Mobile Computing (PM) 61
Google Maps External Library • com. google. android. maps • 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-on • Add a uses-library element to your application's manifest file, to reference the Maps library. – <uses-library android: name= "com. google. android. maps" /> • 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 Key. • Example: <sdk>/add-ons/google_apis-<api-level>/samples/Maps. Demo CEG 436: Mobile Computing (PM) 62
Selected APIs CEG 436: Mobile Computing (PM)
android. hardware • Camera class is used to set image capture settings, start/stop preview, snap pictures, and retrieve frames for encoding for video. • Geomagnetic. Field estimates magnetic field at a given point on Earth, and to compute the magnetic declination from true north. • Sensor Class representing a sensor. Sensor. Event holds information such as the sensor's type, the time-stamp, accuracy and sensor's data. Sensor. Manager lets you access the device's sensors. CEG 436: Mobile Computing (PM) 64
android. bluetooth • Bluetooth. Adapter Represents the local Bluetooth radio. Entry-point for all Bluetooth interaction. Instantiate a Bluetooth. Device using a known MAC address, and create a Bluetooth. Server. Socket. • Bluetooth. Profile. Service. Listener An interface for notifying Bluetooth. Profile IPC clients when they have been connected or disconnected to the service. • Bluetooth. Socket A connected or connecting Bluetooth socket. CEG 436: Mobile Computing (PM) 65
android. nfc • Nfc. Manager This is the high level manager, used to obtain this device's Near Field Communication (NFC) Nfc. Adapter. Acquire an instance: get. System. Service(String) CEG 436: Mobile Computing (PM) 66
android. net • Connectivity. Manager Class that answers queries about the state of network connectivity. • Local. Socket. Address A UNIX-domain (AF_LOCAL) socket address. • Network. Info Describes the status of a network interface of a given type (currently either Mobile or Wifi). • Uri. Builder. Helper class for building or manipulating URI references. CEG 436: Mobile Computing (PM) 67
android. net. wifi • Wifi. Configuration. A class representing a configured Wi-Fi network, including the security configuration. • Wifi. Manager. This class provides the primary API for managing all aspects of Wi-Fi connectivity. CEG 436: Mobile Computing (PM) 68
Device Administration • Device. Admin. Receiver Can interpret raw intent actions that are sent by the system. • Device. Policy. Manager manages policies for one or more Device. Admin. Receivers • Device. Admin. Info specify metadata for a device administrator component. • Device Administration API sample CEG 436: Mobile Computing (PM) 69
References • http: //developer. android. com • CEG 436: Mobile Computing (PM) 70
- Slides: 70