MobAppDev: Started Services, Intent Services, & Notifications


Published on

Started Services, Intent Services, & Notifications

Published in: Software
1 Like
  • Be the first to comment

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

No notes for slide

MobAppDev: Started Services, Intent Services, & Notifications

  1. 1. Android MobAppDev Started Services, Intent Services, & Notifcations Vladimir Kulyukin
  2. 2. Outline Tasks & Services ● Started Services ● Started vs. Bound Services ● Notifications ● Intent Services ●
  3. 3. Tasks & Services
  4. 4. Three Thread Rules Android UI widgets are not thread-safe ● Main Thread (aka the UI thread) should not be blocked ● UI widgets cannot be accessed from outside the UI thread ●
  5. 5. Long Running Tasks ● ● ● ● What happens if you need to run a long-term job that is independent of any UI Enter services A Service is a way for an application to request Android to keep some task running for a while If there is not enough RAM, Android may still terminate services
  6. 6. What is a Service? ● ● ● A Service is an application component for performing long running operations in the background Services have no user interfaces, and are started by other application components Services may continue to run in the background even after the user switches to another application different from the application that started them
  7. 7. What Are Services For? ● Services have four primary areas of use:  Network transactions  Intensive I/O  Interaction with content providers  Multimedia operations (e.g., music, video)
  8. 8. Two Types of Services ● ● ● There are two board types of Android services: started (aka local) and bound (aka remote) Started services are typically used within one application Bound services are used for inter-process communication (IPC) that goes across application boundaries
  9. 9. Started Services ● ● ● ● A started service is started by an application component (typically, an activity) that calls startService() A started service usually performs a single operation that does not return results back 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 itself
  10. 10. Bound Services ● ● ● A Service is bound when an application component binds to it by calling bindService() A Bound service 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 Java
  11. 11. 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 (the garbage collection inference counting principle) When a bound service has no bound components, it can be destroyed by Android
  12. 12. Services vs. Threads ● ● ● By default, services run on the main thread of their hosting processes & do not spawn their own threads unless explicitly told to do so What it means is that if you have a service doing a lot of CPU-intensive and/or blocking work (networking, playing music, I/O), the service may cause its hosting application to become non-responsive: this is the infamous Application Not Responding (ANR) Error A service may spawn their own threads
  13. 13. Services vs. Threads ● ● ● A service should be seriously considered only when you need to run some task in the background when the user is not interacting with the computation A thread is called for only when you need to do some task off the main thread only when the user is interacting with the application Example: when you need to TTS some text only when the user is looking at the screen, you should use a Thread (AsyncTask can also be used)
  14. 14. Access to Services ● ● ● Any application component can access a started or bound service A service can be declared private in AndroidManifest.xml If a service is private, any access from other applications is blocked
  15. 15. START_STICKY vs. START_NOT_STICKY ● ● ● These codes are used when the mobile device runs out of memory and kills the started service When a service is started with START_STICKY, Android re-creates it when it has enough memory after the service is terminated When a service is started with START_NOT_STICKY, Android does not bother to re-create it after it kills it
  16. 16. Started Services
  17. 17. Problem Write an application that uses a started service to compute all Catalan numbers less than or equal to 100,000 and displays them one by one in the status bar. source code is in StartedCatalanNumberService repo
  18. 18. Catalan Numbers ● ● ● ● Catalan numbers are a sequence of natural numbers The numbers get their name after Eugene Charles Catalan, a 19th century Belgian mathematician Catalan numbers figure prominently in combinatorics and recursive definitions Here are a few initial members of the Catalan sequence: 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, ...
  19. 19. Catalan Numbers: Two Interpretations ● One interpretation of Catalan numbers is the number of binary trees with n nodes: C(0) = 1, C(1) = 1, C(2) = 2, C(3) = 5 N=0 N=1 N=2 N=3 NULL ● Another interpretation is the number of expressions with n pairs of parentheses properly matched
  20. 20. Catalan Number Formula C0 = 1 C n +1 2( 2n + 1) = Cn n+2
  21. 21. Notifications ● ● ● Notifications notify the user of background events when no activity is present NotificationManager handles Notifications Notifications can be used to display messages & icons on the status bar, vibrate the phone, play audio alerts, broadcast intents, & flash lights
  22. 22. Notifications ● ● ● Notifications are helpful when multiple services are running the background doing different computations The user is unlikely to pay attention to any of them Displaying messages and icons on the status bar alerts the user to what is going on in the background
  23. 23. Getting NoficationManager & Notification.Builder // Two objects are needed to handle Notifications: NotificationManager // and Notification.Builder NotificationManager mNoteMngr = null; Notification.Builder mNoteBuilder = null; mNoteMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNoteBuilder = new Notification.Builder(getApplicationContext()); Source code is in
  24. 24. Constructing a Notification // Suppose that R.drawable.ornament_00 is a PNG image in /res/drawable; // mVibrationPattern is a pattern of vibrations (an array of long numbers); // msg is a string to display on the status bar // PendingIntent is an intent triggered by some event later mNoteBuilder.setSmallIcon(R.drawable.ornament_00) .setTicker(msg) .setWhen(System.currentTimeMillis()) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) .setVibrate(mVibrationPattern); Notification note = mNoteBuilder.getNotification(); note.setLatestEventInfo(getApplicationContext(), SERVICE_CONTENT_TITLE, msg, mPendingIntent); Source code is in
  25. 25. Screenshots
  26. 26. Solution ● ● ● Extend the Service class In the extended class (, define a NotificationManager member In the extended class, define a worker thread class ( CatalanServiceWorker) that implements the Runnable interface
  27. 27. Solution ● ● ● ● The worker thread and NotificationManager objects are created and in onCreate() The worker thread is also started in onCreate() Place ornament_00.png (the icon to be displayed in the status bar – you can replace it with your own image) in /res/drawable Declare the service in AndroidManifest.xml
  28. 28. Source Code Highlights
  29. 29. Starting a Service startService(new Intent(StartedCatalanServiceAct .this .getApplicationContext(), CatalanNumberService.class)); Source code is in
  30. 30. Stopping a Service stopService(new Intent(StartedCatalanServiceAct .this .getApplicationContext(), CatalanNumberService.class)); Source code is in
  31. 31. Spawning Threads from Services public void onCreate() { // Create and start a worker thread. mWorkerThread = new Thread( new CatalanServiceWorker(), SERVICE_NAME ); // Get off the main thread mWorkerThread.start(); } Source code is in
  32. 32. Stopping Services stopService(new Intent(StartedCatalanServiceAct .this .getApplicationContext(), CatalanNumberService.class)); Source code is in
  33. 33. Declaring Services in AndroidManifest.xml <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".StartedCatalanServiceAct" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="CatalanNumberService" /> </application> Source code is in AndroidManifest.xml
  34. 34. Intent Services
  35. 35. Alternatives to Multi-Threading ● ● ● ● What if you do not want to live dangerously with threads? 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 IntentService
  36. 36. What is IntentService? ● ● ● ● IntentService is a subclass of Service IntentService handles all start requests one at a time IntentService is the best option if multithreading is not needed All one needs to do is to implement onHandleIntent() which receives the intent for each start request
  37. 37. What Does IntentService Do? ● ● ● ● Creates a worker thread that executes all intents given to onStartCommand() The worker thread is different from your application's 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()
  38. 38. 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 service
  39. 39. 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 user. source code is in StartedSumIntentService repo
  40. 40. Screenshots 1 2 3 4
  41. 41. Source Code Highlights
  42. 42. Implementation of onHandleIntent() protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); String catSumKey = mRes.getString(R.string.cat_sum); String fibSumKey = mRes.getString(R.string.fib_sum); String nKey = mRes.getString(R.string.n_key); // 1. check if the bundle contains cat_sum or fib_sum key and n_key if ( (extras.containsKey(catSumKey) || extras.containsKey(fibSumKey)) && extras.containsKey(nKey) ) { long n = extras.getLong(nKey); // 2. if cat_sum key is present, then compute the catalan sum and post a notification message // on the status bar if ( extras.containsKey(catSumKey) ) { postNotificationMessage(compileCatNote(n, catalanSum(n))); } else { // 3. if fibo_sum key is present, then compute the fibonacci sum and post a notification message on // the status bar postNotificationMessage(compileFiboNote(n, fiboSum(n))); }} else { postNotificationMessage("Wrong arguments"); } mNoteMngr.cancel(R.string.app_id); } source code is in
  43. 43. Starting an IntentService // 1. Create an Intent to run StartedSumIntentService.class Intent i1 = new Intent(getApplicationContext(), StartedSumIntentService.class); long n1 = Long.parseLong(mNEdtTxt.getText().toString().toString()); // 2. Put two key-value pairs (<cat_sum, true> and <n, n1>) into the Intent's bundle i1.putExtra(mRes.getString(R.string.cat_sum), true); i1.putExtra(mRes.getString(R.string.n_key), n1); // 3. start service with the created intent startService(i1); source code is in