Mobile Application Development: Lecture 18


Published on

Mobile Application Development: Lecture 18

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

Mobile Application Development: Lecture 18

  1. 1. Mobile Application Development Lecture 18 Vladimir Kulyukin Department of Computer Science Utah State University
  2. 2. Outline ● Processes, Threads, & Services ● HTTP Consumption ● XML Consumption
  3. 3. Processes, Threads, & Services
  4. 4. Motivation ● Android is unique in the way that it allows multiple applications at the same time ● Experienced developers who have worked on other 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 ecosystem
  5. 5. How is Android Different? ● Users are not required to close applications ● Fast (less than 1 second) application launch ● All applications are created equal: APIs are the same for Android developers no matter where or for whom they work
  6. 6. Processes & Applications ● On 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 down
  7. 7. Processes & 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 thread
  8. 8. Three Basic Thread Rules ● 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 thread
  9. 9. 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 notifications
  10. 10. 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 them ● If a service starts a thread, the service must manage it
  11. 11. 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)
  12. 12. 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 boundaries
  13. 13. 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 can stop itself
  14. 14. 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
  15. 15. 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 Android
  16. 16. Services & Threads ● Services run in the main thread of their hosting process by default (this can be changed via the android:process attribute in the service declaration) ● 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) Error
  17. 17. Best Developer Practices ● 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 to run a time-consuming task, define a started service ● If you need a set of tasks that various applications can use, define a bound service
  18. 18. HTTP Consumption
  19. 19. Consuming HTTP Services ● HTTP Services are the most frequently consumed services on Android ● You typically use 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- consuming
  20. 20. HTTP Consumption Steps // 1. obtain an http client HttpClient hc = new DefaultHttpClient(); // 2. Constructor a http request (either get or put) HttpGet req = new HttpGet(); // 3. Set the URI of the request req.setURI(uri); // 4. Execute request and obtain response HttpResponse res = hc.execute(req); // 5. Put the content of the response into buffered reader in = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
  21. 21. HTTP Consumption Steps // 6. Create a string buffer StringBuffer sb = new StringBuffer(""); String currLine = ""; // 7. Get the system line separator (e.g., n) String LNSPRTR = System.getProperty("line.separator"); // 8. Read the content from the buffered reader into the string buffer while ( (currLine = in.readLine()) != null ) { sb.append(currLine + LNSPRTR); } // 9. close buffered reader in.close(); // 10. Convert string buffer to string and return return sb.toString();
  22. 22. Example ● Write an application that uses a Service with a thread to write a text file and the html of a URL (url is specified as a string constant) to the sdcard ● The service launches the thread on startup ● The thread generates the text update message and obtains the URLs html, writes them on to the sdcard and goes to sleep for 5 seconds ● The service does thread management: the thread is shut down when the service is destroyed; the thread is shut down and automatically restarted when the activity is paused after the user pressed Start Service
  23. 23. UpdateServiceApp Project Take a look at the source code in and of the UpdateServiceApp project
  24. 24. XML Consumption
  25. 25. XML Parsing on Android ● Java + XML = Portable Code + Portable Data ● Android framework strength is that it leverages Java and, through Java, XML ● Android SDK does not support everything available in JRE, but it does support a significant part of it, including most of Javas XML APIs
  26. 26. DOM vs SAX ● Android supports both Javas Simple API for XML (SAX) and the Document Object Model (DOM) ● To the best of my knowledge, Android does yet not support Streaming API for XML (StAX) but does provide a functionally equivalent library ● To the developer, SAX and DOM on Android are the same as they are on JRE
  27. 27. SAX vs DOM ● SAX does not read an XML document into memory ● SAX parses documents piece by piece through event handlers implemented by the programmer ● DOM does read an entire XML document into memory and then gives the programmer a set of methods to manipulate the document tree ● DOM tends to be easier to program than SAX ● Both SAX and DOM are useful tools: it is all about space/time tradeoffs and the needs of a specific application
  28. 28. Example ● Write an application that parses a cloud-stored XML file that specifies a table of book titles, extracts individual book titles, converts them into strings, and saves them in a text file on the sdcard ● The application uses the HTTP service to obtain the XML file and then uses the DOM parser to parse the XML document
  29. 29. XMLDbTableBuilder Project Take a look at the source code in and of the XMLDbTableBuilder project
  30. 30. Cloud-Stored XML <?xml version="1.0" encoding="utf-8" ?> <book_title_table> <book_title> <title>The Essential Rumi</title> <author>Jalal adDin Rumi</author> <translator>C. Barks, J. Moyne</translator> <isbn>9780062509581</isbn> <price>17.51</price> </book_title> <book_title> <title>The Illuminated Rumi</title> <author>Jalal adDin Rumi</author> <translator>C. Barks</translator> <isbn>9780767900027</isbn> <price>25.04</price> </book_title> ... </book_title_table>
  31. 31. References ● ● ● ● Source code is available here
  32. 32. Feedback Bugs to vladimir dot kulyukin at gmail dot com