When to use a Service or AsyncTask or Handler?

前端 未结 5 819
夕颜
夕颜 2020-12-22 23:20

Can someone tell me the TRUE difference?

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-22 23:33

    Service

    A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with.

    When to use?

    Task with no UI, but shouldn’t be too long. Use threads within service for long tasks. Long task in general.

    Trigger: Call to method onStartService()

    Triggered from: Any Thread

    Runs on: Main thread of its hosting process. The service does not create its own thread and does not run in a separate process (unless you specify otherwise)

    Limitations / Drawbacks: May block main thread


    AsyncTask

    AsyncTask enables the proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

    When to use?

    Small task having to communicate with main thread For tasks in parallel use multiple instances OR Executor Disk-bound tasks that might take more than a few milliseconds

    Trigger: Call to method execute()

    Triggered from: Main Thread

    Runs on: Worker thread. However, Main thread methods may be invoked in between to publish progress.

    Limitations / Drawbacks:

    • One instance can only be executed once (hence cannot run in a loop)
    • Must be created and executed from the Main thread

    Ref Link

提交回复
热议问题