Android Programming: Lecture 12


Published on

1) Review of Started Services
2) Started Intent Services
3) Shared Agenda
4) Loopers and Handlers
5) Bound (Remote) Services
6) Android Interface Definition Language
7) Class home page is at

Published in: Software, Technology, Education
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Android Programming: Lecture 12

  1. 1. Android Programming Lecture 12 Vladimir Kulyukin Department of Computer Science Utah State
  2. 2. Resources Source code and presentation materials for this lecture are available at
  3. 3. Outline ● Review of Started Services ● Started Intent Services ● Shared Agenda ● Loopers and Handlers ● Bound (Remote) Services ● Android Interface Definition
  4. 4. Review: Started (Local) Services ● Started services are consumed by applications that host them ● A Started service is started by an application component (typically, an activity) that calls startService() ● Once started, a service may run in the background indefinitely even after the component that started it is
  5. 5. Review: Started (Local) Services ● A Started service usually performs a single operation that does not return any result to the caller directly ● The results are returned to the caller indirectly: a message on the status bar, saved file, updated content provider, etc ● After its work is done, a started service should stop
  6. 6. Review: Catalan Numbers ● Catalan numbers are a sequence of natural numbers ● The numbers get their name after Eugene Charles th Catalan, a 19 century Belgian mathematician ● Catalan numbers figure prominently in combinatorics and recursive definitions ● Here are a few initial members of the Catalan sequences for n = 0, 1, 2, 3 ● 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786,
  7. 7. Review: Catalan Number Formula C0 = 1 2( 2n + 1) C n+ 1 = Cn n+
  8. 8. Alternatives to Multi-Threading ● What if you do not want to live dangerously? ● Suppose that you do not need multi-threading ● Suppose your application needs to handle one background request at a time ● Are there safer alternatives to creating and managing worker threads? ● The answer is – yes, it is
  9. 9. Started Intent
  10. 10. What is IntentService? ● IntentService is a subclass of Service ● IntentService handles all start requests one at a time ● IntentService is the best option if multi-threading is not needed ● All one needs to do is to implement onHandleIntent() which receives the intent for each start
  11. 11. What Does IntentService Do? ● Creates a worker thread that executes all intents given to onStartCommand() ● The worker thread is different from your applications main thread ● Creates a work queue that passes one intent at a time to onHandleIntent(): no multi-threading is guaranteed ● Stops the service after all start intents have been processed: no need to call stopSelf()
  12. 12. What Does IntentService Do? ● Provides a default implementation of onBind() that returns null ● Provides a default implementation of onStartCommand() that puts intents to the work queue and then to onHandleIntent() ● What do you need to do if you want to use IntentService – Implement onHandleIntent() – Implement a constructor for the
  13. 13. The Problem Write an application that uses an IntentService to compute the sum of the first n members of the Catalan sequences and the Fibonacci sequence; the sequence is selected by the
  14. 14. StartedSumIntentService Project
  15. 15. StartedSumIntentService Project Source
  16. 16. Shared
  17. 17. Shared Agenda ● Sequential processing of messages and tasks is accomplished on Android via the Shared Agenda Thread pattern ● Agenda is an AI term frequently used in AI robotics ● Pipeline is an OS term commonly used in the concurrency
  18. 18. Shared Agenda ● Shared Agenda Thread pattern is used on many robotic platforms (ActivMedia robots is one example) ● Shared Agenda pattern or something very similar to it are used in many UI frameworks such as Swing or Adobe Flex ● The general idea is to use the Shared Agenda thread to push sequential tasks off the main UI
  19. 19. Shared Agenda ● Shared Agenda is a thread that holds a queue of messages and tasks ● A message (android.os.Message) is a data structure for someone else to process ● A task (java.lang.Runnable) is a unit of CPU work that can be
  20. 20. Shared Agenda ● When there are no tasks on the Shared Agenda, it blocks ● Other threads can push new messages onto the queue at any time ● When there are messages on the queue, the Shared Agenda processes them one after
  21. 21. android.os.Looper and android.os.Handler ● Looper is a class that turns a thread into a shared agenda thread with a message queue ● Handler is a class that other threads can use to push messages to the shared agenda ● The term Looper emphasizes the fact that a Looper object loops over the message queue executing messages one after
  22. 22. Threads and android.os.Handler ● Thread in Android has a MessageQueue ● MessageQueue is a queue of Message objects ● Handler is associated with a specific Thread and its MessageQueue ● Handler, once associated with a Thread, can send Messages and Runnables to the Threads MessageQueue and execute them as they come off the
  23. 23. android.os.Handler ● Handlers are used to schedule Messages and Runnables ● You can enqueue Runnables with – post(Runnable) – postAtTime(Runnable, long) – postDelayed(Runnable, long) ● The enqueued Runnables are called as they are received ● You can send messages with – sendEmptyMessage(int) – sendMessage(Message) – sendMessageAtTime(Messasge, int) – sendDelayedMessage(Message, long)
  24. 24. android.os.Looper ● Looper runs a message loop for a Thread ● Handler is typically used in conjunction with a Looper ● Looper.prepare() creates a message queue ● Looper.loop() processes messages as long as the Thread
  25. 25. Preparing Looper and Binding Handler public void run() { try { // 1. Turn the current thread into a shared agenda mLooper.prepare(); // 2. Bind a handler to the looper mHandler() = new Handler(); // 3. Start running the looper mLooper.loop(); } catch ( Throwable ex ) { // handle exception } }
  26. 26. Posting Messages from Other Threads // Suppose that another thread has access to the Handler // object stored in mHandler. Then it can post a message as follows: Runnable() { @Override public void run() { // do the message related work } });
  27. 27. StartedSumLooperService
  28. 28. The Problem Write an application that uses a Handler and a Looper in a started service. The Handler is associated with a Thread. The Handler receives messages about computing Catalan or Fibonacci sums and handles them accordingly. The results are posted in the status
  29. 29. StartedSumLooperService Project
  30. 30. StartedSumLooperService Project Source
  31. 31. StartedSumLooperService2
  32. 32. The Problem Rewrite the StartedSumLooperService to eliminate the status bar image leftover problem. The application still uses handlers and loopers but shares the information with the main UI activity via shared memory in the application extension
  33. 33. StartedSumLooperService2
  34. 34. StartedSumLooperService2 Project Source
  35. 35. Remember to Change AndroidManifest.xml <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:name=".StartedSumLooperServiceApp"> <activity android:label="@string/app_name" android:name=".StartedSumLooperService2Act" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="StartedSumLooperService2" /> </application>
  36. 36. Bound (Remote)
  37. 37. RMI ● RMI applications comprise two separate components: server and client ● Server creates remote objects, publishes references to those objects, waits for clients to invoke references on those objects ● Client obtains remote references to objects and invokes published methods on those
  38. 38. Bound (Remote) Services ● Started Android services are consumed by applications that host them ● Bound services are consumed by other applications via the Remote Procedure Call (RPC) mechanism ● All RPC solutions require Interface Definition Languages (IDL) that define for clients remote procedure calls that they can request various services to
  39. 39. Bound Services ● A Service is bound when an application component binds to it by calling bindService() ● Bound services offers a client-server interface that components can use to interact with the service, send requests, receive results, and do other IPC stuff ● Bound services offer the same type of functionality as remote method invocation (RMI) in
  40. 40. Bound Services ● Multiple components can bind to a bound service at once ● A Bound service is alive as long as at least one component is bound to it ● When a bound service has no bound components, it is destroyed by
  41. 41. Basics of Bound Services ● A bound service is an implementation of the Service class ● The developer of a bound service must implement onBind() that returns an IBinder object ● The IBinder object defines the programmatic interface the clients can use to interact with the
  42. 42. Basics of Bound Services ● A client binds to the service by executing bindService() ● A client must provide an instance of ServiceConnection object that monitors the connection b/w the client and the service ● When Android creates the connection b/w the client and the service it calls onServiceConnected() on the ServiceConnection object that returns the IBinder object to the
  43. 43. Multiple Clients ● It is possible and allowed for multiple clients to connect to a Service at once ● Android OS calls the bound services onBind() only once ● After the first call the same IBinder object is returned to all subsequent client calls ● When the last client unbinds from the service, the service is destroyed by
  44. 44. Android Interface Definition Language ● AIDL is similar to other IDLs ● AIDL defines a programmatic contract b/w the client and the service that they can use to do interprocess communication (IPC) ● On Android, one process is not allowed to access the memory of another process ● The processes need to decompose the objects into OS primitives and marshall them across process
  45. 45. Android Interface Definition Language ● Marshalling code is difficult to write and debug ● AIDL compiler handles the generation of that code for you ● Calls to an AIDL interface are direct function calls ● No assumptions should be made about the thread in which those calls
  46. 46. AIDL and Thread Safety ● Calls from local process are executed in the same thread that make the calls ● If only local threads access the services, you may not need AIDL ● Calls from a remote process are dispatched from a thread pool that platform maintains inside the service process ● AIDL interfaces must be thread
  47. 47. References & Reading Suggestions ● ● ● ● Rito Meier, “Professional Android 2 Application Development” ● Hashimi, Komatineni, MacLean, “Pro Android 2”
  48. 48. Feedback Bugs, errors to vladimir dot kulyukin at gmail dot