Android Programming: Lecture 11

2,909 views

Published on

1) Multitasking in Android
2) Development and Consumption of Services
3) Started Services
4) Bound Services
5) Consumption of HTTP Services
6) Development of Started Services
7) Class home page is at http://vkedco.blogspot.com/2011/08/android-programming-home.html

Published in: Software, Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,909
On SlideShare
0
From Embeds
0
Number of Embeds
1,336
Actions
Shares
0
Downloads
1
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Android Programming: Lecture 11

  1. 1. Android Programming Lecture 11 Vladimir Kulyukin Department of Computer Science Utah State Universitywww.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Outline ● Multitasking in Android ● Development and Consumption of Services – Started Services – Bound Services ● Consumption of HTTP Services ● Development of Started Serviceswww.youtube.com/vkedco www.vkedco.blogspot.com
  3. 3. Multitasking in Androidwww.youtube.com/vkedco www.vkedco.blogspot.com
  4. 4. Motivation ● Android is unique in the way that it allows multiple applications at the same time ● Developers experienced on different platforms sometimes find the way Android works surprising ● Basic understanding of how multitasking works on Android is fundamental for designing and implementing applications that function properly in the Android Ecosystemwww.youtube.com/vkedco www.vkedco.blogspot.com
  5. 5. Key Android Features ● Users are not required to close applications ● Strict limits on hard memory ● Fast (less than 1 second) application launch ● All applications are created equal: APIs are the same for Android developers no matter where and for what company they workwww.youtube.com/vkedco www.vkedco.blogspot.com
  6. 6. Processes and Applications ● In Android, processes and applications are not tightly coupled ● Multiple applications may share the same process ● One application may use multiple processes during its lifetime ● When the user leaves an application, its process may be kept around in the background or, if the system runs low on memory, shut downwww.youtube.com/vkedco www.vkedco.blogspot.com
  7. 7. Processes and Threads ● When an application starts and the application does not have any other components running, Android starts a new Linux process with a single thread of execution ● By default, all components of the same application run in the same process and thread called the Main Thread ● If an application component starts and there already exists a process for that application (because another component of that application is running), that component uses the same process and the same threadwww.youtube.com/vkedco www.vkedco.blogspot.com
  8. 8. Processes and Threads ● It is possible for different components in an application to run in separate processes and can create threads within a process ● Process specification can be done in the manifest file by specifying the android:process attribute ● The android:process attribute is supported by <application>, <activity>, <service>, <receiver>, and <provider> ● Each component may run in its own process, share a process with another component, etc ● Advice: do not do it unless you really need itwww.youtube.com/vkedco www.vkedco.blogspot.com
  9. 9. Process Lifecycle ● Android places all processes in an importance hierarchy ● Importance is a function of the components running in that process and the state of those components ● Processes with the lowest importance are terminated first, then those with the next lowest importance, and so onwww.youtube.com/vkedco www.vkedco.blogspot.com
  10. 10. Five Levels of Importance Hierarchy ● Foreground ● Visible ● Service ● Background ● Emptywww.youtube.com/vkedco www.vkedco.blogspot.com
  11. 11. Foreground Process ● Hosts an Activity with which the user interacts (onResume() has been called) ● Hosts a Service bound to the Activity with which the user interacts ● Hosts a Service running in foreground (startForeground() has been called) ● Hosts a Service executing one of its lifecycle callbacks: onCreate(), onStartCommand(), or onDestroy() ● Hosts a BroadcastReceiver that is executing onReceive()www.youtube.com/vkedco www.vkedco.blogspot.com
  12. 12. Visible Process ● Hosts an Activity that is not in foreground but visible to the user (onPause() has been called) ● Hosts a Service bound to a visible or foreground Activitywww.youtube.com/vkedco www.vkedco.blogspot.com
  13. 13. Background and Empty Processes ● Hosts an Activity that is not currently visible to the user (Activitys onStop() has been called) ● Background processes are kept in the LRU (least recently used) list: processes associated with an Activity most recently used are last to be terminated ● Empty process does not hold any active application components ● Empty processes may be kept around for caching purposes to improve startup timeswww.youtube.com/vkedco www.vkedco.blogspot.com
  14. 14. Key Point To Remember Android does not shut down processes cleanlywww.youtube.com/vkedco www.vkedco.blogspot.com
  15. 15. Three Thread Rules ● Always remember that Android UI widgets are not thread-safe ● Never block the Main Thread (aka the UI thread) ● Do not access UI widgets from outside the UI threadwww.youtube.com/vkedco
  16. 16. Do Not Do This public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = processNetworkImage("http://somecompay.com/image.png"); mImageView.setImageBitmap(b); } }).start(); }www.youtube.com/vkedco www.vkedco.blogspot.com
  17. 17. Do This Instead public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = processNetworkImage("http://somecompany.com/image.png"); mImageView.post(new Runnable() { public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start(); }www.youtube.com/vkedco www.vkedco.blogspot.com
  18. 18. Three Thread Rules ● Always remember that Android UI widgets are not thread-safe ● Never block the Main Thread (aka the UI thread) ● Do not access UI widgets from outside the UI threadwww.youtube.com/vkedco www.vkedco.blogspot.com
  19. 19. Long-Running Tasks ● If Android can kill any application at any time, how can one do long-running tasks? ● Enter services ● A Service is a way for an application to request Android to keep it running for a while ● If there is not enough RAM, Android may still terminate services ● Services may negotiate non-stop status through notificationswww.youtube.com/vkedco www.vkedco.blogspot.com
  20. 20. Processes and Applications ● In Android, processes and applications are not tightly coupled ● Multiple applications may share the same process ● One application may use multiple processes during its lifetime ● When the user leaves an application, its process may be kept around in the background or, if the system runs low on memory, shut downwww.youtube.com/vkedco www.vkedco.blogspot.com
  21. 21. Development and Consumption of Serviceswww.youtube.com/vkedco www.vkedco.blogspot.com
  22. 22. What is a Service? ● A Service is an application component for performing long-running operations in the background ● Services have no user interfaces ● Services 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 themwww.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. What Are Services For? ● Services have four primary areas of use: – Network transactions – Intensive I/O – Interaction with content providers – Multimedia operations (e.g., playing music)www.youtube.com/vkedco www.vkedco.blogspot.com
  24. 24. Two Types of Services ● There are two types of services in the Android Ecosystem: started (aka local) and bound (aka remote) ● Started services are used within one application ● Bound services are used for inter-process communication (IPC) that goes across application boundarieswww.youtube.com/vkedco www.vkedco.blogspot.com
  25. 25. Started Services ● 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 destroyed ● 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 itselfwww.youtube.com/vkedco www.vkedco.blogspot.com
  26. 26. 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 Javawww.youtube.com/vkedco www.vkedco.blogspot.com
  27. 27. 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 Androidwww.youtube.com/vkedco www.vkedco.blogspot.com
  28. 28. Services and Threads ● Services run in the main thread of their hosting processes ● Services 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) Errorwww.youtube.com/vkedco www.vkedco.blogspot.com
  29. 29. A Few Tips ● Get off the Main Thread as soon as you can and as often as you can ● Keep the Main Thread dedicated to user interactions with your applications activities ● If you need a one-time time-consuming task, define a started service ● If you need a set of tasks that various applications can use, define a bound servicewww.youtube.com/vkedco www.vkedco.blogspot.com
  30. 30. Consumption of HTTP Serviceswww.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. Consuming HTTP Services ● HTTP Services are the most frequently consumed services on Android ● You can use either GET or POST methods ● Steps of consuming HTTP services: – Create an HttpClient – Create an Http method – Execute the request – Convert the response to String with BufferedReader – Try executing the request several times – Do it in a background service if HTML parsing is time- consumingwww.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. HTTP Consumption: Useful Classes ● HttpParams – collection of HTTP protocol and framework parameters ● Scheme – a specific protocol scheme, such as http or https ● SchemeRegistry – a set of supported protocol schemes ● ClientConnectionManager – interface for managing client connections ● ThreadSafeClientConnManager – class for managing a pool of safe client connectionswww.youtube.com/vkedco www.vkedco.blogspot.com
  33. 33. The Problem Write an application that uses the GET method to obtain the source of a user-specified URL and returns it as a stringwww.youtube.com/vkedco www.vkedco.blogspot.com
  34. 34. HttpGetURLSource Project Demowww.youtube.com/vkedco www.vkedco.blogspot.com
  35. 35. HttpGetURLSource Project Source Codewww.youtube.com/vkedco www.vkedco.blogspot.com
  36. 36. Sharing Consumed HTTP Results ● Is there a way to share consumed HTTP results with other activities within the same application? ● You can extend the Application class ● Application class is a singleton ● You can create a member variable in your extension ● Activities can use that member variable as shared memory ● You have to do synchronization ● You have to provide for the case of application shutdown – Override your extensions onLowMemory() – Make activities more robustwww.youtube.com/vkedco www.vkedco.blogspot.com
  37. 37. HttpGetURLSource2 Project Demowww.youtube.com/vkedco www.vkedco.blogspot.com
  38. 38. Remember To Change Manifest File <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:name=".HttpGetApp" > <activity ...> </activity> <activity ...> </activity> </application>www.youtube.com/vkedco www.vkedco.blogspot.com
  39. 39. HttpGetURLSource2 Project Source Codewww.youtube.com/vkedco www.vkedco.blogspot.com
  40. 40. Development of Started Serviceswww.youtube.com/vkedco www.vkedco.blogspot.com
  41. 41. 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, ...www.youtube.com/vkedco www.vkedco.blogspot.com
  42. 42. 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, ...www.youtube.com/vkedco www.vkedco.blogspot.com
  43. 43. 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 matchedwww.youtube.com/vkedco www.vkedco.blogspot.com
  44. 44. Catalan Number Formula C0 = 1 2( 2n + 1) C n+ 1 = Cn n+ 2www.youtube.com/vkedco www.vkedco.blogspot.com
  45. 45. StartedCatalanService Projectwww.youtube.com/vkedco www.vkedco.blogspot.com
  46. 46. The 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 barwww.youtube.com/vkedco www.vkedco.blogspot.com
  47. 47. StartedCatalanService Project Demo 1www.youtube.com/vkedco www.vkedco.blogspot.com
  48. 48. Solution ● Extend the Service class ● In the extended class (CatalanNumberService), define a NotificationManager member ● In the extended class, define a worker thread class (CatalanServiceWorker) that implements the Runnable interfacewww.youtube.com/vkedco www.vkedco.blogspot.com
  49. 49. 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 notification item to be displayed in the status bar) in /res/drawable-hdpi ● Declare the service in AndroidManifest.xmlwww.youtube.com/vkedco www.vkedco.blogspot.com
  50. 50. StartedCatalanService Project Source Codewww.youtube.com/vkedco www.vkedco.blogspot.com
  51. 51. StartedCatalanService Project Demo 2www.youtube.com/vkedco www.vkedco.blogspot.com
  52. 52. Observations on StartedCatalanService ● If a component starts the service by calling startService() (which results in a call to onStartCommand()), then the service remains running until it stops itself with stopSelf() or another component stops it by calling stopService() ● Even when stopService() is called, Runnable objects do not appear to be stopped until Android calls onDestroy() ● Be careful about using the status bar, especially putting drawables in there, unless you are reasonably certain that the user will not mindwww.youtube.com/vkedco www.vkedco.blogspot.com
  53. 53. Remember to Declare 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>www.youtube.com/vkedco www.vkedco.blogspot.com
  54. 54. Started Intent Serviceswww.youtube.com/vkedco www.vkedco.blogspot.com
  55. 55. 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 IntentServicewww.youtube.com/vkedco www.vkedco.blogspot.com
  56. 56. 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 requestwww.youtube.com/vkedco www.vkedco.blogspot.com
  57. 57. 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()www.youtube.com/vkedco www.vkedco.blogspot.com
  58. 58. 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 servicewww.youtube.com/vkedco www.vkedco.blogspot.com
  59. 59. References & Reading Suggestions ● http://developer.android.com/resources/articles/multitasking- android-way.html ● http://en.wikipedia.org/wiki/Catalan_number ● Rito Meier, “Professional Android 2 Application Development” ● Hashimi, Komatineni, MacLean, “Pro Android 2”www.youtube.com/vkedco www.vkedco.blogspot.com
  60. 60. Feedback Bugs, errors to vladimir dot kulyukin at gmail dot comwww.youtube.com/vkedco www.vkedco.blogspot.com

×