Efficient Android Threading

Book description

Multithreading is essential if you want to create an Android app with a great user experience, but how do you know which techniques can help solve your problem? This practical book describes many asynchronous mechanisms available in the Android SDK, and provides guidelines for selecting the ones most appropriate for the app you’re building.

Author Anders Goransson demonstrates the advantages and disadvantages of each technique, with sample code and detailed explanations for using it efficiently. The first part of the book describes the building blocks of asynchronous processing, and the second part covers Android libraries and constructs for developing fast, responsive, and well-structured apps.

  • Understand multithreading basics in Java and on the Android platform
  • Learn how threads communicate within and between processes
  • Use strategies to reduce the risk of memory leaks
  • Manage the lifecycle of a basic thread
  • Run tasks sequentially in the background with HandlerThread
  • Use Java’s Executor Framework to control or cancel threads
  • Handle background task execution with AsyncTask and IntentService
  • Access content providers with AsyncQueryHandler
  • Use loaders to update the UI with new data

Table of contents

  1. Dedication
  2. Preface
    1. Audience
    2. Contents of This Book
    3. Conventions Used in this Book
    4. Using Code Examples
    5. Safari® Books Online
    6. How to Contact Us
    7. Acknowledgements
  3. 1. Android Components and the Need for Multiprocessing
    1. Android Software Stack
    2. Application Architecture
      1. Application
      2. Components
        1. Activity
        2. Service
        3. ContentProvider
        4. BroadcastReceiver
    3. Application Execution
      1. Linux Process
      2. Lifecycle
        1. Application start
        2. Application termination
    4. Structuring Applications for Performance
      1. Creating Responsive Applications Through Threads
    5. Summary
  4. I. Fundamentals
    1. 2. Multithreading in Java
      1. Thread Basics
        1. Execution
        2. Single-Threaded Application
        3. Multithreaded Application
          1. Increased resource consumption
          2. Increased complexity
          3. Data inconsistency
      2. Thread Safety
        1. Intrinsic Lock and Java Monitor
        2. Synchronize Access to Shared Resources
          1. Using the intrinsic lock
          2. Using explicit locking mechanisms
        3. Example: Consumer and Producer
      3. Task Execution Strategies
        1. Concurrent Execution Design
      4. Summary
    2. 3. Threads on Android
      1. Android Application Threads
        1. UI Thread
        2. Binder Threads
        3. Background Threads
      2. The Linux Process and Threads
        1. Scheduling
          1. Priority
          2. Control groups
      3. Summary
    3. 4. Thread Communication
      1. Pipes
        1. Basic Pipe Use
        2. Example: Text Processing on a Worker Thread
      2. Shared Memory
        1. Signaling
      3. BlockingQueue
      4. Android Message Passing
        1. Example: Basic Message Passing
        2. Classes Used in Message Passing
          1. MessageQueue
          2. MessageQueue.IdleHandler
          3. Example: Using IdleHandler to terminate an unused thread
        3. Message
          1. Initialized
          2. Pending
          3. Dispatched
          4. Recycled
        4. Looper
          1. Looper termination
          2. The UI thread Looper
        5. Handler
          1. Setup
          2. Message creation
          3. Message insertion
          4. Example: Two-way message passing
          5. Message processing
        6. Removing Messages from the Queue
        7. Observing the Message Queue
          1. Taking a snapshot of the current message queue
          2. Tracing the message queue processing
      5. Communicating with the UI Thread
      6. Summary
    4. 5. Interprocess Communication
      1. Android RPC
        1. Binder
      2. AIDL
        1. Synchronous RPC
        2. Asynchronous RPC
      3. Message Passing Using the Binder
        1. One-Way Communication
        2. Two-Way Communication
      4. Summary
    5. 6. Memory Management
      1. Garbage Collection
      2. Thread-Related Memory Leaks
        1. Thread Execution
          1. Inner classes
          2. Static inner classes
          3. The lifecycle mismatch
        2. Thread Communication
          1. Sending a data message
          2. Posting a task message
      3. Avoiding Memory Leaks
        1. Use Static Inner Classes
        2. Use Weak References
        3. Stop Worker Thread Execution
        4. Retain Worker Threads
        5. Clean Up the Message Queue
      4. Summary
  5. II. Asynchronous Techniques
    1. 7. Managing the Lifecycle of a Basic Thread
      1. Basics
        1. Lifecycle
        2. Interruptions
        3. Uncaught Exceptions
      2. Thread Management
        1. Definition and Start
          1. Anonymous inner class
          2. Public thread
          3. Static inner class thread definition
          4. Summary of options for thread definition
        2. Retention
          1. Retaining a thread in an Activity
          2. Retaining a thread in a Fragment
      3. Summary
    2. 8. HandlerThread: A High-Level Queueing Mechanism
      1. Fundamentals
      2. Lifecycle
      3. Use Cases
        1. Repeated Task Execution
        2. Related Tasks
          1. Example: Data persistence with SharedPreferences
        3. Task Chaining
          1. Example: Chained network calls
        4. Conditional Task Insertion
      4. Summary
    3. 9. Control over Thread Execution Through the Executor Framework
      1. Executor
      2. Thread Pools
        1. Predefined Thread Pools
        2. Custom Thread Pools
          1. ThreadPoolExecutor configuration
        3. Designing a Thread Pool
          1. Sizing
          2. Dynamics
          3. Bounded or unbounded task queue
          4. Thread configuration
          5. Extending ThreadPoolExecutor
        4. Lifecycle
        5. Shutting Down the Thread Pool
        6. Thread Pool Uses Cases and Pitfalls
          1. Favoring thread creation over queuing
          2. Handling preloaded task queues
          3. The danger of zero core threads
      3. Task Management
        1. Task Representation
        2. Submitting Tasks
          1. Individual submission
          2. invokeAll
          3. invokeAny
        3. Rejecting Tasks
      4. ExecutorCompletionService
      5. Summary
    4. 10. Tying a Background Task to the UI Thread with AsyncTask
      1. Fundamentals
        1. Creation and Start
        2. Cancellation
        3. States
          1. Example: Limiting an AsyncTask execution to one at the time
      2. Implementing the AsyncTask
        1. Example: Downloading Images
      3. Background Task Execution
        1. Application Global Execution
        2. Execution Across Platform Versions
        3. Custom Execution
          1. Example: Nonglobal sequential execution
      4. AsyncTask Alternatives
        1. When an AsyncTask Is Trivially Implemented
        2. Background Tasks That Need a Looper
        3. Local Service
        4. Using execute(Runnable)
      5. Summary
    5. 11. Services
      1. Why Use a Service for Asynchronous Execution?
      2. Local, Remote, and Global Services
      3. Creation and Execution
      4. Lifecycle
      5. Started Service
        1. Implementing onStartCommand
        2. Options for Restarting
        3. User-Controlled Service
          1. Example: Bluetooth connection
        4. Task-Controlled Service
          1. Example: Concurrent download
      6. Bound Service
        1. Local Binding
      7. Choosing an Asynchronous Technique
      8. Summary
    6. 12. IntentService
      1. Fundamentals
      2. Good Ways to Use an IntentService
        1. Sequentially Ordered Tasks
          1. Example: Web service communication
        2. Asynchronous Execution in BroadcastReceiver
          1. Example: Periodical long operations
      3. IntentService Versus Service
      4. Summary
    7. 13. Access ContentProviders with AsyncQueryHandler
      1. Brief Introduction to ContentProvider
      2. Justification for Background Processing of a ContentProvider
      3. Using the AsyncQueryHandler
        1. Example: Expanding Contact List
        2. Understanding the AsyncQueryHandler
        3. Limitations
      4. Summary
    8. 14. Automatic Background Execution with Loaders
      1. Loader Framework
        1. LoaderManager
          1. initLoader vs restartLoader
        2. LoaderCallbacks
        3. AsyncTaskLoader
      2. Painless Data Loading with CursorLoader
        1. Using the CursorLoader
        2. Example: Contact list
        3. Adding CRUD Support
          1. Example: Use CursorLoader with AsyncQueryHandler
      3. Implementing Custom Loaders
        1. Loader Lifecycle
        2. Background Loading
          1. Example: Simple custom loader
        3. Content Management
        4. Delivering Cached Results
        5. Example: Custom File Loader
        6. Handling Multiple Loaders
      4. Summary
    9. 15. Summary: Selecting an Asynchronous Technique
      1. Keep It Simple
      2. Thread and Resource Management
      3. Message Communication for Responsiveness
      4. Avoid Unexpected Task Termination
      5. Easy Access to ContentProviders
    10. A. Bibliography
      1. Books
      2. Articles
      3. Presentations
  6. Index
  7. Colophon
  8. Copyright

Product information

  • Title: Efficient Android Threading
  • Author(s): Anders Goransson
  • Release date: May 2014
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449364090