Skip to content

Instantly share code, notes, and snippets.

@joseph-zhong
Last active December 31, 2016 04:24
Show Gist options
  • Save joseph-zhong/a49f2234971c2dc0289cd337b1675be6 to your computer and use it in GitHub Desktop.
Save joseph-zhong/a49f2234971c2dc0289cd337b1675be6 to your computer and use it in GitHub Desktop.
Android: Difference between Thread, AsyncTask, etc

Please read this blog

Difference between Android Service, Thread, IntentService and AsyncTask

Service

  • Task with no UI, but shouldn't be too long. Use threads within service for long tasks.
  • Triggered from any thread
  • Runs on Main Thread
  • Limitations:
    • May block main thread

Thread

  • Long task in general.
  • For tasks in parallel use Multiple threads (traditional mechanisms)
  • Triggered from any thread
  • Runs on its own thread
  • Limitations:
    • Manual thread management
    • Code may become difficult to read

IntentService

  • Long task usually with no communication to main thread.
  • If communication is required, can use main thread handler or broadcast intents
  • When callbacks are needed (Intent triggered tasks).
  • Triggered on Main Thread (Intent is received on main thread and then worker thread is spawed)
  • Runs on Separate worker thread
  • Limitations:
    • Cannot run tasks in parallel.
    • Multiple intents are queued on the same worker thread.

AsyncTask

  • Small task having to communicate with main thread.
  • For tasks in parallel use multiple instances OR Executor
  • Triggered on Main Thread
  • Runs on Worker thread. However, Main thread methods may be invoked in between to publish progress.
  • Limitations:
    • one instance can only be executed once, thus cannot run in a loop
    • Must be created and executed from the Main thread
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment