Mobile Application Development                         Lecture 18                    Vladimir Kulyukin             Departm...
Outline   ●       Processes, Threads, & Services   ●       HTTP Consumption   ●       XML Consumptionhttp://www.youtube.co...
Processes, Threads, & Serviceshttp://www.youtube.com/vkedco   http://www.vkedco.blogspot.com
Motivation   ●       Android is unique in the way that it allows       multiple applications at the same time   ●       Ex...
How is Android Different?   ●       Users are not required to close applications   ●       Fast (less than 1 second) appli...
Processes & Applications   ●       On Android, processes and applications are not       tightly coupled   ●       Multiple...
Processes & Threads   ●       When an application starts and the application does not       have any other components runn...
Three Basic Thread Rules   ●     Remember that Android UI widgets are     not thread-safe   ●     Never block the Main Thr...
Long-Running Tasks   ●       If Android can kill any application at any time,       how can one do long-running tasks?   ●...
What is a Service?   ●       A Service is an application component for performing       long-running operations in the bac...
What Are Services For?   ●       Services have four primary areas of       use:         – Network transactions         – I...
Two Types of Services   ●       There are two types of services in the       Android Ecosystem: started (aka local) and   ...
Started Services   ●       A Started service is started by an application component       (typically, an activity) that ca...
Bound Services   ●       A Service is bound when an application       component binds to it by calling bindService()   ●  ...
Bound Services   ●       Multiple components can bind to a bound       service at once   ●       A Bound service is alive ...
Services & Threads   ●       Services run in the main thread of their hosting process       by default (this can be change...
Best Developer Practices   ●       Get off the Main Thread as soon as you can and       as often as you can   ●       Keep...
HTTP Consumptionhttp://www.youtube.com/vkedco   http://www.vkedco.blogspot.com
Consuming HTTP Services   ●       HTTP Services are the most frequently consumed services on       Android   ●       You t...
HTTP Consumption Steps        // 1. obtain an http client        HttpClient hc = new DefaultHttpClient();        // 2. Con...
HTTP Consumption Steps    // 6. Create a string buffer    StringBuffer sb = new StringBuffer("");    String currLine = "";...
Example   ●       Write an application that uses a Service with a thread to       write a text file and the html of a URL ...
UpdateServiceApp Project                          Take a look at the source code in                          ThreadedUpdat...
XML Consumptionhttp://www.youtube.com/vkedco   http://www.vkedco.blogspot.com
XML Parsing on Android   ●       Java + XML = Portable Code + Portable       Data   ●       Android framework strength is ...
DOM vs SAX   ●       Android supports both Javas Simple API for       XML (SAX) and the Document Object Model       (DOM) ...
SAX vs DOM   ●       SAX does not read an XML document into memory   ●       SAX parses documents piece by piece through e...
Example   ●       Write an application that parses a cloud-stored       XML file that specifies a table of book titles,   ...
XMLDbTableBuilder Project                          Take a look at the source code in                          XMLDbTableBu...
Cloud-Stored XML                      <?xml version="1.0" encoding="utf-8" ?>                      <book_title_table>     ...
References   ●       http://en.wikipedia.org/wiki/Document_Object_Model   ●       http://developer.android.com/reference/j...
Feedback        Bugs to vladimir dot kulyukin at gmail dot comhttp://www.youtube.com/vkedco   http://www.vkedco.blogspot.com
Upcoming SlideShare
Loading in...5
×

Mobile Application Development: Lecture 18

625

Published on

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
625
On Slideshare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Mobile Application Development: Lecture 18"

  1. 1. Mobile Application Development Lecture 18 Vladimir Kulyukin Department of Computer Science Utah State Universityhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  2. 2. Outline ● Processes, Threads, & Services ● HTTP Consumption ● XML Consumptionhttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  3. 3. Processes, Threads, & Serviceshttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  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 ecosystemhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 workhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 downhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 threadhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 threadhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 notificationshttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 ithttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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)http://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 boundarieshttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 itselfhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 Javahttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 Androidhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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) Errorhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 servicehttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  18. 18. HTTP Consumptionhttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  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- consuminghttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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()));http://www.youtube.com/vkedco www.vkedco.blogspot.com
  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();http://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 Servicehttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  23. 23. UpdateServiceApp Project Take a look at the source code in ThreadedUpdateService.java and UpdateServiceAct.java of the UpdateServiceApp projecthttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  24. 24. XML Consumptionhttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com
  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 APIshttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 JREhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 applicationhttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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 documenthttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  29. 29. XMLDbTableBuilder Project Take a look at the source code in XMLDbTableBuilder.java and XMLDbTableBuilderActAct.java of the XMLDbTableBuilder projecthttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  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>http://www.youtube.com/vkedco www.vkedco.blogspot.com
  31. 31. References ● http://en.wikipedia.org/wiki/Document_Object_Model ● http://developer.android.com/reference/javax/xml/parsers/DocumentBuilderFactory.html ● http://developer.android.com/reference/javax/xml/parsers/DocumentBuilder.html ● Source code is available herehttp://www.youtube.com/vkedco www.vkedco.blogspot.com
  32. 32. Feedback Bugs to vladimir dot kulyukin at gmail dot comhttp://www.youtube.com/vkedco http://www.vkedco.blogspot.com

×